Implementing Unique Request IDs in Laravel

Learn how to enhance your Laravel application's logging and monitoring capabilities by implementing unique request IDs.

Implementing Unique Request IDs in Laravel

April 27, 2024

Utilizing Request IDs to Enhance Monitoring and Logging in Laravel

Integrating unique request IDs into your Laravel application can significantly enhance its monitoring and logging capabilities. This feature enables you to easily track and trace requests, improving the overall observability of your application.

To implement this feature, we'll create a new middleware using the following command:

php artisan make:middleware AddRequestID

 

Next, navigate to app/Http/Middleware/AddRequestID.php and add the following code

<?php

namespace App\Http\Middleware;

use Closure;
use Illuminate\Http\Request;
use Symfony\Component\HttpFoundation\Response;

class AddRequestID
{
    /**
     * Handle an incoming request.
     *
     * @param  \Closure(\Illuminate\Http\Request): (\Symfony\Component\HttpFoundation\Response)  $next
     */
    public function handle(Request $request, Closure $next): Response
    {
        $request->headers->set('X-Request-ID', uniqid());

        return $next($request);
    }
}

 

Register the new Middleware in bootstrap/app.php

  ->withMiddleware(function (Middleware $middleware) {
        $middleware->append(
            \App\Http\Middleware\AddRequestID::class
        );
    })

 

Now, for easy access to the request ID, we will add a macro to the Request class. To do this, navigate to app/Providers/AppServiceProvider.php and add the following code to the boot method:

use Illuminate\Http\Request;

/**
  * Bootstrap any application services.
  */
public function boot(): void
{
    Request::macro('id', function (): ?string {
        return $this->header('X-Request-ID');
    });
}

 

You can access the Request ID using the 'id()' method

// With dependency Injection

$request->id() 

// ... or using the request helper function

request()->id()