Do you want to laravel track page views? In this tutorial, we will see visitor counter laravel 9 application. We need to see how our page views. So let's see how we can implement how to count a single post view in Laravel 9 application.
We can implement page view counter in laravel using cyrildewit laravel
page view counter package. But in this tutorial, I do not use the package. When a user can click a single post link and will go to the single post page controller then we will just increment our database field view_count. See the below code -
app/Http/Controller/PostController.php
class PostController extends Controller
{
public function post(post $post)
{
$Key = 'blog' . $post->id;
if (\Session::has($Key)) {
\DB::table('posts')
->where('id', $post->id)
->increment('view_count', 1);
\Session::put($Key, 1);
}
// Write your code which you want
}
}
Or simply use this:
class PostController extends Controller
{
public function post(post $post)
{
\DB::table('posts')
->where('id', $post->id)
->increment('view_count', 1);
}
// Write your code which you want
}
}
Look, here we just increment our view_count field when a user clicks a post and visits a single page. That's it.
#laravel