For your information. If you increment read count on the controller without any check then read count may not be accurate because people can refresh and increase it. So add cookie after visitor read then check for cookie in future. By this, you can have more accurate unique visits.
public function show(Post $post)
{
if(Cookie::get($post->id)!=''){
Cookie::set('$post->id', '1', 60);
$post->incrementReadCount();
}
return view('post.show', compact($post));
}
public function show(Post $post, Request $request )
{
if(! Auth::check()){//guest user identified by ip
$cookie_name = (Str::replace('.','',($request->ip())).'-'. $post->id);
} else {
$cookie_name = (Auth::user()->id.'-'. $post->id);//logged in user
}
if(Cookie::get($cookie_name) == ''){//check if cookie is set
$cookie = cookie($cookie_name, '1', 60);//set the cookie
$post->incrementReadCount();//count the view
return response()
->view('posts.show',[
'post' => $post])
->withCookie($cookie);//store the cookie
} else {
return view('posts.show',[
'post' => $post]);//this view is not counted
}
}
Fair enough. I tried to explain the easiest way to accomplish it since no specific requirements were given.
Without going so far, this forum's thread count works in a similar fashion. Just refresh the page and watch the read counter go up. But sure, for a blog post you might want to have a more accurate count.
I guess the appropriate way is to make a middleware with only string:
$request->post->increment('views_count');
The view counting is not a vote and it is not nesessary protect it against multiple reloading.
By the way, don't use cookie to store info about post viewing. The size and amount of records are limited. In the end server will refused to set cookies and generate 502 bad gateway.