Back
Adding Request Context in Laravel Applications
Laravel's Context facade enhances application insight by allowing you to add persistent metadata throughout your request lifecycle. This context automatically enriches your logs with valuable debugging information.
<?php
use Illuminate\Support\Facades\Context;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Str;
class RequestContext
{
public function __construct()
{
Context::add('request_id', Str::uuid()->toString());
}
public function addUserContext()
{
if (Auth::check()) {
Context::add('user_id', Auth::id());
Context::add('user_type', Auth::user()->type);
}
}
public function logAction(string $action)
{
Log::info("User performed {$action}");
}
}
Let's explore a practical example using request context in a middleware and API request logging:
<?php
namespace App\Http\Middleware;
use Closure;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Context;
use Illuminate\Support\Str;
class ApiRequestLogger
{
public function handle(Request $request, Closure $next)
{
// Add basic request context
Context::add('request_id', Str::uuid()->toString());
Context::add('path', $request->path());
Context::add('method', $request->method());
// Add user context if authenticated
if ($request->user()) {
Context::add('user_id', $request->user()->id);
Context::add('api_key', $request->user()->api_key);
}
// Add performance metrics
$startTime = microtime(true);
$response = $next($request);
Context::add('response_time', round((microtime(true) - $startTime) * 1000, 2));
Context::add('status_code', $response->getStatusCode());
// Log the API request
Log::info('API request processed');
return $response;
}
}
The Context facade enriches your application's logging by providing valuable metadata that persists throughout the request lifecycle, making debugging and monitoring more effective.