如何在Laravel中创建受欢迎的帖子5.4

时间:2017-07-29 04:35:57

标签: php laravel-5.4

我有函数show()来显示帖子的详细信息,这是我的代码:

public function show(Post $post)
    {
      //This line code was used to increment post when someone hit the post
      $viewCount = $post->view_count + 1;
      $post->update(['view_count' => $viewCount]);

      $next_id = Post::where('id', '>', $post->id)->min('id');
      $prev_id = Post::where('id', '<', $post->id)->max('id');

      return view('site.show', compact('post'))
                                ->with('next', Post::find($next_id))
                                ->with('prev', Post::find($prev_id));
    }

但问题是,当有人刷新页面或点击帖子时,它会一遍又一遍地增加。我的问题是如何使用会话或IP地址来解决这个问题,以防止来自同一个用户?

我是从laracasts得到的,但我不知道如何使用我的代码实现它:

$blogKey = 'blog_' . $id;

// Check if blog session key exists
// If not, update view_count and create session key
if (!Session::has($blogKey)) {
    Post::where('id', $id)->increment('view_count');
    Session::put($blogkey, 1);
}

以下是我修改的最终代码:

public function show(Post $post)
    {
        $siteKey = $post->id;
        // Check if site session key exists
        if (!Session::has($siteKey)) {
        // If not, update view_count and create session key
            Post::where('id', $post->id)->increment('view_count');
        //Set the session key so we don't increment for the session duration
            Session::put($siteKey, 1);
        }

      $next_id = Post::where('id', '>', $post->id)->min('id');
      $prev_id = Post::where('id', '<', $post->id)->max('id');

      return view('site.show', compact('post'))
                                ->with('next', Post::find($next_id))
                                ->with('prev', Post::find($prev_id));
    }

1 个答案:

答案 0 :(得分:0)

代码非常自我解释,但这里有评论。您正在使用会话来防止多个视图计数。见下面的评论。

$blogKey = 'blog_' . $post->id;

//Check if the session key has not been set for the post
if (!Session::has($blogKey)) {

    //If there is no session set, increment the counter
    $viewCount = $post->view_count + 1;
    $post->update(['view_count' => $viewCount]);

    //Set the session key so we don't increment for the session duration
    Session::put($blogkey, 1);
}