Kam*_*med 0 php cookies laravel laravel-4
我正在创建一个简单的博客,用户可以在其中添加、更新和查看帖子。我已经在帖子中实现了查看次数功能,该功能显示了帖子的查看次数。为此,我所做的是:
创建了一个事件监听器:
Event::listen('post.viewed', 'PostHandler@updatePostViewsAction');
创建了PostHandler
和updatePostViewsAction
class PostHandler
{
public function handle()
{
//
}
public function updatePostViewsAction( $post )
{
// Update view counter of post
$post->views_count = $post->views_count + 1;
$post->save();
}
}
Run Code Online (Sandbox Code Playgroud)
这工作正常,并且观看次数正在成功更新。但后来我决定对视图进行唯一计数。为此,我尝试使用 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);
}
}
}
Run Code Online (Sandbox Code Playgroud)
但它似乎不起作用,因为views_count 每次都在增加。谁能告诉我,我在这里做错了什么?
小智 5
为了使用 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);
}
}
Run Code Online (Sandbox Code Playgroud)
来自 Laravel 文档http://laravel.com/docs/requests#cookies:
为下一个响应排队 Cookie
如果您想在创建响应之前设置 cookie,请使用 Cookie::queue() 方法。cookie 将自动附加到您的应用程序的最终响应中。