I am creating a simple blog in which a user can add, update and view posts. I have implemented the views count functionality in the post that shows the number of views on the post. For that, what I did is:
-
Created an event listener:
Event::listen('post.viewed', 'PostHandler@updatePostViewsAction');
-
Created the
PostHandler
andupdatePostViewsAction
class PostHandler { public function handle() { // } public function updatePostViewsAction( $post ) { // Update view counter of post $post->views_count = $post->views_count + 1; $post->save(); } }
This is working fine and the views count is succesfuly being updated. But later on I decided to make the views to be uniquely counted. For this, I have tried using the cookies i.e. create a cookie on users computer, whenever he views a post and increment the views_count
. If the users comes back again and views the post again, check if there is a cookie available, if it is available then don't increment the views_count
, otherwise increment that. Below is, how I have implemented this:
class PostHandler
{
public function handle()
{
//
}
public function updatePostViewsAction( $post )
{
if ( !Cookie::get('post_viewed') ) {
// Update view counter of post
$post->views_count = $post->views_count + 1;
$post->save();
Cookie::forever('post_viewed', true);
}
}
}
But it doesn't seem to work, as the views_count is getting incremented each and every time. Can anyone please tell me, what am I doing wrong here?