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 →
Decide with Jev: Make Failed AI Requests Safe in Laravel image

Decide with Jev: Make Failed AI Requests Safe in Laravel

Read article
Black Friday: Learn the habits behind AI workflows that work image

Black Friday: Learn the habits behind AI workflows that work

Read article
Laravel Black Friday and Cyber Monday Deals 2026 image

Laravel Black Friday and Cyber Monday Deals 2026

Read article
pgjumbo: A PostgreSQL Client for macOS, Windows, and Linux image

pgjumbo: A PostgreSQL Client for macOS, Windows, and Linux

Read article
Laranon: Reversible PII Anonymization for Laravel and LLMs image

Laranon: Reversible PII Anonymization for Laravel and LLMs

Read article
PHP 8.6 is released!  image

PHP 8.6 is released!

Read article