laravelhttptcprequesttracker

how can i know or set id for any HTTP request in Laravel


I want to analyze how the user works on the website. For example, he opens the pages of the site in order:

-> main page -> product page -> detail page -> ...

That's why I use the "tracker" system and send an HTTP request to the server on every page of the site. It is very difficult to compare requests when there are so many in the moment.

but i think now if i can know or set id for HTTP requests (KeepAlive connections) is so well.

someone can show a helpful way for me.

tnx


Solution

  • You can do so by using middleware

    Create a middleware to track routes:

    php artisan make:middleware LogRouteMiddleware
    

    LogRouteMiddleware

    class LogRouteMiddleware
    {
        public function handle(Request $request, Closure $next)
        {
            $currentRoute = url()->current();// or route name: Route::currentRouteName();
            $previousRoute = url()->previous(); //or route name: app('router')->getRoutes()->match(app('request')->create(url()->previous()))->getName()
    
            // Store them in DB or Logs. up to you
            return $next($request);
        }
    }
    

    app\Http\Kernel.php

    protected $routeMiddleware = [
        // other middleware entries
        'log.route' => \App\Http\Middleware\LogRouteMiddleware::class,
    ];
    

    web.php\api.php

    Route::group(['middleware' => ['log.route']], function() {
        ... // all routes you want to track
    });
    

    Accessing current route

    Accessing previous route

    URL method