Close Menu
    DevStackTipsDevStackTips
    • Home
    • News & Updates
      1. Tech & Work
      2. View All

      Sunshine And March Vibes (2025 Wallpapers Edition)

      May 16, 2025

      The Case For Minimal WordPress Setups: A Contrarian View On Theme Frameworks

      May 16, 2025

      How To Fix Largest Contentful Paint Issues With Subpart Analysis

      May 16, 2025

      How To Prevent WordPress SQL Injection Attacks

      May 16, 2025

      Microsoft has closed its “Experience Center” store in Sydney, Australia — as it ramps up a continued digital growth campaign

      May 16, 2025

      Bing Search APIs to be “decommissioned completely” as Microsoft urges developers to use its Azure agentic AI alternative

      May 16, 2025

      Microsoft might kill the Surface Laptop Studio as production is quietly halted

      May 16, 2025

      Minecraft licensing robbed us of this controversial NFL schedule release video

      May 16, 2025
    • Development
      1. Algorithms & Data Structures
      2. Artificial Intelligence
      3. Back-End Development
      4. Databases
      5. Front-End Development
      6. Libraries & Frameworks
      7. Machine Learning
      8. Security
      9. Software Engineering
      10. Tools & IDEs
      11. Web Design
      12. Web Development
      13. Web Security
      14. Programming Languages
        • PHP
        • JavaScript
      Featured

      The power of generators

      May 16, 2025
      Recent

      The power of generators

      May 16, 2025

      Simplify Factory Associations with Laravel’s UseFactory Attribute

      May 16, 2025

      This Week in Laravel: React Native, PhpStorm Junie, and more

      May 16, 2025
    • Operating Systems
      1. Windows
      2. Linux
      3. macOS
      Featured

      Microsoft has closed its “Experience Center” store in Sydney, Australia — as it ramps up a continued digital growth campaign

      May 16, 2025
      Recent

      Microsoft has closed its “Experience Center” store in Sydney, Australia — as it ramps up a continued digital growth campaign

      May 16, 2025

      Bing Search APIs to be “decommissioned completely” as Microsoft urges developers to use its Azure agentic AI alternative

      May 16, 2025

      Microsoft might kill the Surface Laptop Studio as production is quietly halted

      May 16, 2025
    • Learning Resources
      • Books
      • Cheatsheets
      • Tutorials & Guides
    Home»Development»Adding Request Context in Laravel Applications

    Adding Request Context in Laravel Applications

    December 24, 2024

    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 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 

    Hostinger
    Facebook Twitter Reddit Email Copy Link
    Previous ArticlePredictions for software development in 2025
    Next Article Get a Server’s Public IP Address With PHP

    Related Posts

    Security

    Nmap 7.96 Launches with Lightning-Fast DNS and 612 Scripts

    May 17, 2025
    Common Vulnerabilities and Exposures (CVEs)

    CVE-2025-40906 – MongoDB BSON Serialization BSON::XS Multiple Vulnerabilities

    May 17, 2025
    Leave A Reply Cancel Reply

    Continue Reading

    Easily Optimize PDFs in Laravel with the Optimizer Package

    Development

    La Licenza Post-Open di Bruce Perens: Nuove Prospettive per il Software Libero?

    Linux

    How to automate KendoUI dropdown with selenium webdriver and C#

    Development

    The Environmental Impact of AI: Unveiling Its Hidden Costs

    Web Development

    Highlights

    IBM Researchers Introduce AI-Hilbert: An Innovative Machine Learning Framework for Scientific Discovery Integrating Algebraic Geometry and Mixed-Integer Optimization

    July 26, 2024

    Science aims to discover concise, explanatory formulae that align with background theory and experimental data.…

    Privacy Implications and Comparisons of Batch Sampling Methods in Differentially Private Stochastic Gradient Descent (DP-SGD)

    December 2, 2024

    Using deep learning to image the Earth’s planetary boundary layer

    April 18, 2024

    Accelerating MongoDB Migration to Azure with Microsoft Migration Factory

    November 19, 2024
    © DevStackTips 2025. All rights reserved.
    • Contact
    • Privacy Policy

    Type above and press Enter to search. Press Esc to cancel.