Laravel Unique Visitor Counter
In order to implement a unique visitor counter in Laravel, you can follow the steps below:
- Create a new migration using the
php artisan make:migration
command. For example: - In the generated migration file, define the necessary columns for the visitor_counter table. You would typically need columns like
ip_address
andvisited_at
to track the visitor’s IP address and the timestamp of the visit. - Run the migration to create the visitor_counter table in your database:
- Create a new middleware using the
php artisan make:middleware
command. For example: - In the generated middleware file, add the necessary logic to track the visitor’s IP address and save it in the visitor_counter table. You can use the
request()
helper function to access the current request’s IP address: - Register the middleware in the
app/Http/Kernel.php
file by adding it to the$middleware
array: - Finally, you can retrieve the count of unique visitors by querying the visitor_counter table:
php artisan make:migration create_visitor_counter_table --create=visitor_counter
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
class CreateVisitorCounterTable extends Migration
{
public function up()
{
Schema::create('visitor_counter', function (Blueprint $table) {
$table->id();
$table->string('ip_address');
$table->timestamp('visited_at')->useCurrent();
$table->timestamps();
});
}
public function down()
{
Schema::dropIfExists('visitor_counter');
}
}
php artisan migrate
php artisan make:middleware TrackVisitor
namespace App\Http\Middleware;
use Closure;
use Illuminate\Support\Facades\DB;
class TrackVisitor
{
public function handle($request, Closure $next)
{
$ipAddress = $request->ip();
DB::table('visitor_counter')->insert([
'ip_address' => $ipAddress,
]);
return $next($request);
}
}
protected $middleware = [
// Other middlewares
\App\Http\Middleware\TrackVisitor::class,
];
use Illuminate\Support\Facades\DB;
public function uniqueVisitorsCount()
{
return DB::table('visitor_counter')->distinct('ip_address')->count();
}
With the above steps, you will have a visitor_counter table that keeps track of unique visitors based on their IP addresses. The middleware is responsible for inserting a new record with the visitor’s IP address whenever a request is made to your Laravel application.
Note that the above code snippets are just examples, and you may need to modify them according to your specific requirements.