Physical Address

304 North Cardinal St.
Dorchester Center, MA 02124

Implementing A Page View Counter In Laravel

How to implement a total post view counter in Laravel 8?

In this tutorial, I will give you an example of “How to implement a total post view counter in laravel 8”, So you can easily apply it with your laravel 5, laravel 6, laravel 7, and laravel 8 application.

We can say it is going to be a click counter or a single post visitor counter, we will create this post counter using Laravel, If a user visits a page or a post then our Database field name total_views is automatically incremented.

First, what we’re doing here, This is the example :

total post views in laravel

post views counter in laravel

Easy Way to Implement Post View Counter in Laravel

In the application When a user will click a single post link and will go to the single post page controller then we will just increment our database field total_views, See the below example.

Just add a column in your database named the total_views and increment that on every page load to Counting page views with Laravel.

Today we will implement Toal Post views count using the increment method in Laravel.

Increment & Decrement :

The query builder also provides convenient methods for incrementing or decrementing the value of a given column, Both of these methods accept at least one argument: the column to modify, A second argument may be provided to specify the amount by which the column should be incremented or decremented.

For more visit: Increment Method in Laravel.


DB::table('users')->increment('votes');

Let’s get started.

Generating Migration

At first, we create a new migration file for the “posts” table, In your cmd terminal hit the given below command.

 php artisan make:migration create_posts_table

Migration Structure

<?php

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

class CreatePostsTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('posts', function (Blueprint $table) {
            $table->id();
            $table->string('post_author');
            $table->string('post_title');
            $table->string('post_description');
            $table->integer('total_views')->default(0);
            $table->timestamps();
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::dropIfExists('posts');
    }
}

Run Migration

php artisan migrate

Create a Model

php artisan make:model Post

App\Models\Post.php

<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;

class Post extends Model
{
    use HasFactory;
}

Create a Controller

php artisan make:controller PostController

routes\web.php

<?php

use Illuminate\Support\Facades\Route;
use App\Http\Controllers\PostController;


#Post view counter Example
Route::get('/post-create',[PostController::class, 'create'])->name('post.create');
Route::post('/post-store',[PostController::class, 'store'])->name('post.store');
Route::get('/post-list',[PostController::class, 'list'])->name('post.list');
Route::get('/post-view/{id}',[PostController::class, 'view'])->name('post.view');

app\Http\Controllers\PostController.php

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Models\Post;

class PostController extends Controller
{
    public function create()
    {
        return view('post.create');
    }

    public function store(Request $request){
        $post = new Post();
        $post->post_author = $request->title;
        $post->post_title = $request->author;
        $post->post_description = $request->description;
        $post->save();
        return redirect()->route('post.list');

    }

    public function list()
    {
        $posts = Post::get();
        return view('post.list',compact('posts'));
    }

    public function view($id){
        Post::find($id)->increment('total_views');
        $post_detail = Post::find($id);
        return view('post.view',compact('post_detail'));
    }
}

resources\views\post\create.blade.php

implement post view counter in laravel
   <main>
      <div class="container">
         <div class="row justify-content-center">
            <div class="col-lg-6">
               <div class="main">
                  <h3><a>Total Post Views Counter Example in Laravel.</a></h3>
                  <form role="form" action="{{route('post.store')}}" method="post">
                     @csrf
                     <div class="form-group">
                        <label for="title">Post Title <span class="text-danger">*</span></label>
                        <input type="text" name="title" class="form-control" required>
                     </div>
                     <div class="form-group">
                        <label for="author">Post Author<span class="text-danger">*</span></label>
                        <input type="text" name="author" class="form-control" required>
                     </div>
                     <div class="form-group">
                        <label for="description">Post Description <span class="text-danger">*</span></label>
                        <textarea name="description" class="form-control" rows="4" cols="50"></textarea required>
                     </div>
                     <div class="form-group">
                     <button type="submit" class="btn btn btn-secondary">save</button>
                  </form>
               </div>
            </div>
         </div>
      </div>
   </main>
 

resources\views\post\list.blade.php

Laravel unique visitor counter
      <div class="container">
         <h3>Total Post Views Counter Example in Laravel.</h3>
         <br>
         <table class="table">
            <thead>
               <tr>
                  <th>S.no</th>
                  <th>Post Author</th>
                  <th>Post Title</th>
                  <th>Post Decription</th>
                  <th>Action</th>
               </tr>
            </thead>
            <tbody>
               @foreach($posts as $key => $data)
               <tr>
                  <td>{{ $key+1 }}</td>
                  <td>{{ $data->post_author }}</td>
                  <td>{{ $data->post_title }}</td>
                  <td>{{ $data->post_description }}</td>
                  <td><a href="{{route('post.view',$data->id)}}">View</a></td>
               </tr>
            </tbody>
            @endforeach
         </table>
      </div>

resources\views\post\view.blade.php

Increment method in Laravel
<main>
      <div class="container">
         <div class="row justify-content-center">
            <div class="col-lg-6">
               <div class="main">
                  <h3><a>Total Post Views Counter Example in Laravel.</a></h3>
                  <form>
                    <div class="form-group">
                        <label for="views"><strong style="color:red"><u>Total Views</u> : </strong></label>
                        <Span><b>{{$post_detail->total_views}}</b></Span>
                     </div>
                     <div class="form-group">
                        <label for="author">Post Author </label>
                        <input type="text" class="form-control" value="{{$post_detail->post_author}}" disabled>
                     </div>
                     <div class="form-group">
                        <label for="author">Post Title</label>
                        <input type="text" class="form-control" value="{{$post_detail->post_title}}" disabled>
                     </div>
                     <div class="form-group">
                        <label for="description">Post Description</label>
                        <textarea disabled class="form-control" rows="4" cols="50">{{$post_detail->post_description}}</textarea>
                     </div>
                     <div class="form-group">
                     <button type="submit" class="btn btn btn-secondary">save</button>
                  </form>
               </div>
            </div>
         </div>
      </div>
   </main>

Output :

Implementing A Page View Counter In Laravel
Easy Way to Implement Post View Counter in Laravel

In this article, we learned  “How to implement visitor views/visitor counter in Laravel application”, I hope this article will help you with your Laravel application Project.

Also Read : Use of Any Route in Laravel.