Search code examples
phplaravelrequest

Attaching a unique identifier to laravel request


Is there a package for laravel that ads a unique identifier to each request in order to use it also for logs?

For example: I would know that request-id as12121-1212s-121 had an error and I could look into logs for any errors.

That request-id would be seen in the UI and I could debug when getting a printscreen with the error from the client


Solution

  • If you need a unique id per request you can assign a uuid to the request via global middleware.

    For example:

    <?php
    
    namespace App\Http\Middleware;
    
    use Closure;
    use Illuminate\Http\Request;
    use Illuminate\Support\Str;
    
    class RequestUniqueId
    {
        public function handle(Request $request, Closure $next)
        {
            $uuid = (string) Str::uuid();
            $request->headers->set('X-Request-ID', $uuid);
    
            return $next($request);
        }
    }