【问题标题】:Laravel 4 : Cookies for unique visitor countLaravel 4:用于唯一访问者计数的 Cookie
【发布时间】:2014-07-03 11:32:06
【问题描述】:

我正在创建一个简单的博客,用户可以在其中添加、更新和查看帖子。我已经在帖子中实现了查看次数统计功能,该功能可以显示帖子的查看次数。为此,我所做的是:

  1. 创建了一个事件监听器:

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

  2. 创建了PostHandlerupdatePostViewsAction

    class PostHandler
    {
        public function handle()
        {
            // 
        }
    
        public function updatePostViewsAction( $post )
        {
            // Update view counter of post
            $post->views_count = $post->views_count + 1;
            $post->save();
        }
    }
    

工作正常,观看次数已成功更新。但后来我决定将观看次数设为唯一计数。为此,我有 尝试使用 cookie,即在用户计算机上创建 cookie, 每当他查看帖子并增加 views_count 时。如果用户再次返回并再次查看帖子,请检查是否有可用的 cookie,如果可用 则不要增加 views_count 否则递增。下面是我是如何实现的:

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);
        }
    }
}

但它似乎不起作用,因为 views_count 每次都在增加。谁能告诉我,我在这里做错了什么?

【问题讨论】:

  • 您确定 cookie 确实已创建吗?使用浏览器的开发者工具进行检查。

标签: php cookies laravel laravel-4


【解决方案1】:

为了使用 Laravel 保存 cookie,您需要将其发送到响应中。但是,您可以通过将 cookie 发送到队列来解决此问题。

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);
    }
}

来自 Laravel 文档http://laravel.com/docs/requests#cookies

为下一个响应排队 Cookie

如果您想在创建响应之前设置 cookie,请使用 Cookie::queue() 方法。 cookie 将自动附加到您的应用程序的最终响应中。

【讨论】:

    猜你喜欢
    • 2021-10-28
    • 1970-01-01
    • 2012-09-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-08-04
    • 2023-03-06
    相关资源
    最近更新 更多