How to Add Visitor Counter or Post View Counter in Laravel?

By Hardik Savani April 16, 2024 Category : Laravel

Hi Dev,

This tutorial will give you an example of laravel post view count. let’s discuss about laravel visitor counter tutorial. you can understand a concept of how to add post visitor counter in laravel. This article goes in detailed on laravel view count. Let's see below example laravel visitor views count tutorial.

In this illustration, we'll demonstrate how to establish a "posts" table that includes a "viewer count" column. Subsequently, we'll construct a list of posts, each accompanied by a "view" button. When a user clicks the "view" button, we will increment the visitor count. Essentially, this procedure will integrate a visitor counter into your Laravel website, allowing you to track post views.

You can add visitor counter with laravel 6, laravel 7, laravel 8, laravel 9, laravel 10 and laravel 11 versions.

Preview:

Let's follow the bellow step to make it done example:

Step 1: Install Laravel

This step is not required; however, if you have not created the laravel app, then you may go ahead and execute the below command:

composer create-project laravel/laravel example-app

Step 2: Create Posts Table using Migration

here, we will create new migration for adding new table posts in users table. so let's run bellow command:

php artisan make:migration create_posts_table

After this command you will find one file in following path "database/migrations" and you have to put bellow code in your migration file for create products table.

<?php

use Illuminate\Database\Migrations\Migration;

use Illuminate\Database\Schema\Blueprint;

use Illuminate\Support\Facades\Schema;

return new class extends Migration

{

/**

* Run the migrations.

*

* @return void

*/

public function up()

{

Schema::create('posts', function (Blueprint $table) {

$table->id();

$table->string('title');

$table->string('slug');

$table->text('body');

$table->integer('viewer')->nullable();

$table->timestamps();

});

}

/**

* Reverse the migrations.

*

* @return void

*/

public function down()

{

Schema::dropIfExists('posts');

}

};

Now you have to run this migration by following command:

php artisan migrate

Step 3: Create Post Model

After create "posts" table you should create Post model for posts, so first create file in this path app/Models/Post.php and put bellow content in Post.php file:

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;

/**

* Write code on Method

*

* @return response()

*/

protected $fillable = [

'title', 'body', 'slug', 'viewer'

];

}

Step 4: Create Factory Class

This step explains how to generate dummy data using factory; this data loads dynamically on page scroll:

php artisan make:factory PostFactory --model=Post

Further, put the below code in database\factories\PostFactory.php:

database\factories\PostFactory.php

<?php

namespace Database\Factories;

use Illuminate\Database\Eloquent\Factories\Factory;

use App\Models\Post;

use Illuminate\Support\Str;

/**

* @extends \Illuminate\Database\Eloquent\Factories\Factory<\App\Models\Post>

*/

class PostFactory extends Factory

{

/**

* The name of the factory's corresponding model.

*

* @var string

*/

protected $model = Post::class;

/**

* Define the model's default state.

*

* @return array

*/

public function definition(): array

{

return [

'title' => $this->faker->text(),

'slug' => Str::slug($this->faker->text()),

'body' => $this->faker->paragraph()

];

}

}

Open terminal, execute the below commands to generate the test data:

php artisan tinker

Post::factory()->count(5)->create()

Step 5: Create Route

In this is step we need to create routes for display posts and view post. so open your "routes/web.php" file and add following route.

routes/web.php

<?php

use Illuminate\Support\Facades\Route;

use App\Http\Controllers\PostController;

/*

|--------------------------------------------------------------------------

| Web Routes

|--------------------------------------------------------------------------

|

| Here is where you can register web routes for your application. These

| routes are loaded by the RouteServiceProvider within a group which

| contains the "web" middleware group. Now create something great!

|

*/

Route::get('posts',[PostController::class,'index'])->name('posts.index');

Route::get('posts/{id}',[PostController::class, 'show'])->name('posts.show');

Step 6: Create Controller

Here,we require to create new controller PostController with index method to display posts and show method for view one post. So let's put bellow code.

app/Http/Controllers/PostController.php

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

use App\Models\Post;

class PostController extends Controller

{

/**

* Write code on Method

*

* @return response()

*/

public function index(Request $request)

{

$posts = Post::paginate(20);

return view('posts', compact('posts'));

}

/**

* Write code on Method

*

* @return response()

*/

public function show($id)

{

$post = Post::find($id);

$post->increment('viewer');

return view('postShow', compact('post'));

}

}

Step 7: Create View File

In Last step, let's create posts.blade.php and data.blade.php for display posts list and put following code:

resources/views/posts.blade.php

<!DOCTYPE html>

<html lang="{{ str_replace('_', '-', app()->getLocale()) }}">

<head>

<meta name="csrf-token" content="{{ csrf_token() }}">

<title>Laravel Post View Count Tutorial - ItSolutionStuff.com</title>

<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.0-beta1/dist/css/bootstrap.min.css">

</head>

<body>

<div class="container mt-5" style="max-width: 750px">

<h1>Laravel Post View Count Tutorial - ItSolutionStuff.com</h1>

<div id="data-wrapper">

@foreach ($posts as $post)

<div class="card mb-2">

<div class="card-body">

<h5 class="card-title">{{ $post->title }}</h5>

{!! Str::limit($post->body, 100) !!}

<br/>

<a href="{{ route('posts.show', $post->id) }}">View</a>

</div>

</div>

@endforeach

</div>

</div>

</body>

</html>

resources/views/postShow.blade.php

<!DOCTYPE html>

<html lang="{{ str_replace('_', '-', app()->getLocale()) }}">

<head>

<meta name="csrf-token" content="{{ csrf_token() }}">

<title>Laravel Post View Count Tutorial - ItSolutionStuff.com</title>

<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.0-beta1/dist/css/bootstrap.min.css">

</head>

<body>

<div class="container mt-5" >

<h1>{{ $post->title }} - ItSolutionStuff.com</h1>

<strong class="text-danger">Total Views: {{ $post->viewer }}</strong>

<p>{!! $post->body !!}</p>

</div>

</body>

</html>

Run Laravel App:

All the required steps have been done, now you have to type the given below command and hit enter to run the Laravel app:

php artisan serve

Now, Go to your web browser, type the given URL and view the app output:

http://localhost:8000/posts

Output:

I hope it can help you...

Tags :
Shares