Member-only story
Enhancing Laravel Applications with Persistent Request Context Using Context Facade
3 min readJan 25, 2025
In Laravel, the Context
facade is a powerful tool that allows developers to add persistent metadata throughout the lifecycle of a request. This metadata automatically enriches application logs with critical debugging and monitoring information, simplifying the process of identifying and resolving issues. By leveraging the Context
facade, you can gain deeper insights into application behavior without manually passing context across different layers.
Here’s an example of how to implement request context tracking in a Laravel application:
use Illuminate\Support\Facades\Context;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Str;
class RequestContext
{
public function __construct()
{
// Automatically add a unique identifier for the request
Context::add('request_id', Str::uuid()->toString());
}
public function addUserContext()
{
// Add user-specific context if authenticated
if (Auth::check()) {
Context::add('user_id', Auth::id());
Context::add('user_type', Auth::user()->type);
}
}
public function logAction(string $action)
{
// Log user actions with enriched context
Log::info("User performed {$action}");
}
}