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 IlluminateSupportFacadesContext;
use IlluminateSupportFacadesAuth;
use IlluminateSupportFacadesLog;
use IlluminateSupportStr;
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 AppHttpMiddleware;
use Closure;
use IlluminateHttpRequest;
use IlluminateSupportFacadesContext;
use IlluminateSupportStr;
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.
The post Adding Request Context in Laravel Applications appeared first on Laravel News.
Join the Laravel Newsletter to get all the latest
Laravel articles like this directly in your inbox.
Source: Read MoreÂ