Easy Way to Implement Post View Counter in Laravel

Today we are going to know how to implement Postor Page views count using Laravel . We can say it is going to be click counter or single post visitor counterWe will create this traffic counter using Laravel. 

If a user visits a page or post then our Database field name view_count is automatically incremented. In this tutorial, we will see how we can create a site visitor counter laravel. Laravel page view counter will be the tutorial today.

So let's see how we can implement how to count a single post view in Laravel 8. We can do it using cyrildewit laravel page view counter package. But in this tutorial, I don't use any packages. I will do it using our own code.

Hope you enjoy this. 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 below code -

 

Read aslo: How to create dynamic xml sitemap in laravel ?

 

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 visit the single page. That's it. 

 

Facebook Github
A web enthusiastic, a self-motivated full-stack software engineer from Dhaka, Bangladesh with experience in developing applications using Laravel , React and Vue js