'Laravel many times route access

I want to know if Laravel has any route control, not for authentication, but for counting access. That is, I need to know the many times I have accessed this route. Is it possible in Laravel?

Or how can I do this? Is it necessary to store in my database?



Solution 1:[1]

I can imagine 2 ways: storing the counter in your DB or using a 3rd party service.

IMO, if you want to keep track of visits, I would recommend using something like Google analytics and relieving your server from unnecessary DB statements.

Anyway, if you still want to do it by yourself, storing a counter in your database is the way. For this purpose, the best approach is by implementing a middleware for the route.

Assuming that you have this route www.mysite.com/my-custom-route defined as

Route::get('/my-custom-route', [MyController::class, 'index']);

You can create a middleware https://laravel.com/docs/9.x/middleware#defining-middleware

<?php
 
namespace App\Http\Middleware;
 
use Closure;
 
class CountVisits
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
        // Yout logic here
        // Increment counter in your DB using eloquent or raw query
 
        return $next($request);
    }
}

Finally, make use of your middleware in your route, so every time the route is reached, the middleware will increment a counter in your DB

use App\Http\Middleware\CountVisits;

Route::get('/my-custom-route', [MyController::class, 'index'])->middleware(CountVisits::class);

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Luciano