Easy Laravel Visitor Counter for your Project

So you want to implement a Visitor Counter on your Laravel application to keep a record of visitors on your website. If you are tired of going through those old Laravel packages and different forms you have come to the right place. In this blog post, I will show you a simple step-by-step process on how you can easily add the Visitor Counter feature to your Laravel project along with the code snippets.

The Main Question

I am sure you might have done your project pretty much. Also if you’re wondering should I start the project from the beginning to add the Visitor Counter the answer is “no“. You can easily implement the code below at any stage of your project.

Steps for Laravel Visitor Counter

Let’s assume you have done all that creating new projects using php artisan serve and the database syncing part adding the database name to the .env file.

1 – Use the command below to create a middleware.

php artisan make:middleware RecordVisitor

The code above will create a new middleware fine at the location YourProjectName\app\Http\Middleware\RecordVisitor.php where all the magic happens.

2 – Now copy and paste the code below to RecordVistor middleware.

<?php

namespace App\Http\Middleware;

use Closure;
use Illuminate\Support\Facades\Request;
use App\Models\Visitors; // Import the Visitors model

class RecordVisitor
{
    public function handle($request, Closure $next)
    {
        $visitDate = now()->format('Y-m-d');
        $ipAddress = Request::ip(); // Get the IP address from the request

        // Check if the IP address has already visited on the current date
        $existingVisitor = Visitors::where('visit_date', $visitDate)
            ->where('ip_address', $ipAddress)
            ->first();

        if ($existingVisitor) {
            // IP address has already visited today, update the visitor count
            $existingVisitor->increment('visitor_count');
        } else {
            // IP address has not visited today, create a new record
            Visitors::create([
                'ip_address' => $ipAddress,
                'visit_date' => $visitDate,
                'visitor_count' => 1,
            ]);
        }

        return $next($request);
    }
}

The above middleware first gets the visitor’s IP Address and checks if or not the IP Address is present in the table on today’s date or not. If the IP address is already available the visitor count will be updated for that IP address or else a new row will be added for that IP Address with today’s date with the default visitor count which is 1.

3 – Make a Model and Migration for the visitors table to record data.

Paste the code below on your IDE console/terminal for creating both migration and model files with one command. The migration file will be created on YourProjectName\database\migrations\visitors.php and the model file will be created on app\Models\Visitors.php

php artisan make:model Visitors --migration

Replace the Visitors.php model with the code below.

<?php

namespace App\Models;

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

class Visitors extends Model
{
    use HasFactory;
    protected $fillable = [
        'visitor_count',
        'visit_date',
        'ip_address'
    ];

}

You also need to change the migration table code to the code below:

<?php

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

return new class extends Migration {
    /**
     * Run the migrations.
     */
    public function up(): void
    {
        Schema::create('visitors', function (Blueprint $table) {
            $table->id();
            $table->string('ip_address');
            $table->date('visit_date');
            $table->unsignedInteger('visitor_count')->default(0);
            $table->timestamps();

            $table->unique(['ip_address', 'visit_date']); // Ensure unique IP and visit_date combination

        });
    }

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

The code above will create a table named visitors in your database with the following structure. Also, don’t forget to save and execute the code below:

php artisan migrate
structure of visitors table in database

4 – Using middleware on routes.

You can now easily use the created middleware on the routes/web.php. Also, make sure all your routes are inside the functions as shown below so that the visitors get counted.

Route::middleware([RecordVisitor::class])->group(function () {

//Routes bellow

Route::get('/',[MasterController::class,'index'])->name('homepage.page');

//Routes above

});

5 – Retrieving the total number of visitors.

The code below can be used to retrieve the total number of visitors from the table easily on any blade file of your choice. Add the codes in the controller file and then pass them into the blade file as a variable.

use App\Models\Visitor; // Import the Visitor model

$totalUniqueIPs = Visitor::distinct('ip_address')->count('ip_address');

Here is a little help for you to retrieve the unique visitors of today.

use App\Models\Visitor; // Import the Visitor model

$visitDate = now()->format('Y-m-d');
$totalVisitorsToday = Visitors::whereDate('visit_date', $visitDate)->count();

Summary

Hope you are happy with the whole blog and have understood many things related to Laravel and Middleware. To sum up, the whole blog firstly we create a middleware that tracks the unique IP of the visitors and update’s it on the database on a daily basis and we retrieve the data using the model through the controller all the way to our blade files.

I would be happy to see your thoughtful are happy comments below. Happy Codding 😄

Leave a Comment