How to Count Visitors on a Website in Laravel 8
Laravel provides several methods to count visitors on a website. Below is an example of how you can implement visitor tracking in Laravel 8:
- First, you need to create a new middleware to handle visitor tracking. Create a new file called “VisitorMiddleware.php” in the “app/Http/Middleware” directory.
- Next, you need to register the middleware in the “app/Http/Kernel.php” file.
- Finally, you can display the visitor count anywhere on your website by accessing the “visitor_count” cache key. For example, you can add the following code in your view:
<?php
namespace App\Http\Middleware;
use Closure;
use Illuminate\Support\Facades\Cache;
class VisitorMiddleware
{
public function handle($request, Closure $next)
{
$expiresAt = now()->addMinutes(10); // Set the cache expiration time
$ipAddress = $request->ip();
// Check if the visitor's IP address is already stored in the cache
if (!Cache::has('visitor_' . $ipAddress)) {
// If not, store the IP address in the cache and increment the visitor count
Cache::put('visitor_' . $ipAddress, true, $expiresAt);
Cache::increment('visitor_count', 1);
}
return $next($request);
}
}
In the example above, we use Laravel’s cache system to store the visitor’s IP address as a key-value pair. We also increment a “visitor_count” cache key to keep track of the total number of visitors.
<?php
// ...
protected $middlewareGroups = [
'web' => [
// ...
\App\Http\Middleware\VisitorMiddleware::class
],
// ...
];
// ...
Make sure you add the middleware in the “web” middleware group, as it should be applied to all web routes.
<div class="visitor-count">
Total Visitors: {{ Cache::get('visitor_count', 0) }}
</div>
The code above retrieves the value of the “visitor_count” cache key from the cache. If the key does not exist, it will default to 0. You can style the “visitor-count” div as needed to display the visitor count on your website.