How to Implement Post View Counter in Laravel 7

Today we are going to know how to implement Post/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 site visitor counter laravel. Laravel page view counter will be the tutorial today. So let's see how we can implement how to count single post view in Laravel 7.

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 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
      }
}

Look , here we just increment our view_count field when a user click a post and visit single page. That's it. 

A web enthusiastic, self-motivated Full-Stack Web Developer from Dhaka, Bangladesh with experience in developing applications using JavaScript, Laravel & Wordpress specifically. Facebook Github Website