Kamran Ahmed
Kamran Ahmed

Reputation: 12438

Laravel 4 : Cookies for unique visitor count

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:

  1. Created an event listener:

    Event::listen('post.viewed', 'PostHandler@updatePostViewsAction');

  2. Created the PostHandler and updatePostViewsAction

    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?

Upvotes: 0

Views: 2326

Answers (1)

danielheyman
danielheyman

Reputation: 66

In order to save a cookie with Laravel, you are required to send it to the response. However, you can workaround it by sending the cookie to the queue.

public function updatePostViewsAction( $post )
{
    if ( !Cookie::get('post_viewed') ) {
        // Update view counter of post
        $post->views_count = $post->views_count + 1;
        $post->save();
        // Create a cookie before the response and set it for 30 days
        Cookie::queue('post_viewed', true, 60 * 24 * 30);
    }
}

Source from Laravel Docs http://laravel.com/docs/requests#cookies:

Queueing A Cookie For The Next Response

If you would like to set a cookie before a response has been created, use the Cookie::queue() method. The cookie will automatically be attached to the final response from your application.

Upvotes: 5

Related Questions