Laravel Tutorials

Adding Request Context in Laravel Applications

Published Updated
Adding Request Context in Laravel Applications image

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.

Harris Raftopoulos photo

Senior Software Engineer • Staff & Educator @ Laravel News • Co-organizer @ Laravel Greece Meetup

Sponsored

serpapi logo
SerpApi

The Web Search API for Your LLM and AI Applications

Visit SerpApi

The latest

View all →
Email Sending and Testing for Laravel in One Account image

Email Sending and Testing for Laravel in One Account

Read article
Decide with Jev: Tie Every AI Check to the Exact Draft image

Decide with Jev: Tie Every AI Check to the Exact Draft

Read article
PIE 1.5 Changes PHP Extension Installs in CI image

PIE 1.5 Changes PHP Extension Installs in CI

Read article
Delete Expired Sessions in Laravel With a Scheduled Command image

Delete Expired Sessions in Laravel With a Scheduled Command

Read article
Pollora: Run WordPress Inside a Laravel Application image

Pollora: Run WordPress Inside a Laravel Application

Read article
Scheduled Session Garbage Collection in Laravel 13.39 image

Scheduled Session Garbage Collection in Laravel 13.39

Read article