Understanding Laravel 12 Context: A Simple Guide with Examples
Laravel's Context feature is like having a shared notebook that travels with your application's requests, jobs, and commands. It lets you store and access information anywhere in your app, and even includes this information in your logs automatically.
What is Context in Laravel 12?
Imagine you're playing a game where you need to pass notes between different players (your application's components). Context is like that note - it carries information from one part of your app to another.
Key Benefits:
- Shared information across different parts of your app
- Automatic logging of context data
- Traceability through distributed systems
Basic Usage Examples
1. Adding Information to Context
use Illuminate\Support\Facades\Context;
// Add single value
Context::add('user_ip', $request->ip());
// Add multiple values
Context::add([
'request_id' => Str::uuid(),
'page_visited' => $request->url()
]);
2. Retrieving Context Data
// Get a single value
$requestId = Context::get('request_id');
// Get multiple values
$data = Context::only(['user_ip', 'page_visited']);
// Get all context
$allContext = Context::all();
3. Real-World Example: Tracking User Activity
Let's create middleware that tracks user activity:
namespace App\Http\Middleware;
use Closure;
use Illuminate\Support\Facades\Context;
use Illuminate\Support\Str;
class TrackUserActivity
{
public function handle($request, Closure $next)
{
Context::add([
'session_id' => session()->getId(),
'user_agent' => $request->userAgent(),
'entry_time' => now()->toDateTimeString()
]);
return $next($request);
}
}
Now any log entries will automatically include this information:
Log::info('User purchased item', ['item_id' => 42]);
Output in logs:
User purchased item {"item_id":42} {"session_id":"abc123","user_agent":"Mozilla/5.0","entry_time":"2023-01-01 12:00:00"}
Advanced Context Features
1. Hidden Context
Sometimes you need to store sensitive data that shouldn't appear in logs:
// Add hidden data
Context::addHidden('api_key', 'secret123');
// Retrieve hidden data
$key = Context::getHidden('api_key');
2. Context Stacks
Stacks are like to-do lists that grow as things happen:
// Track user actions
Context::push('user_actions', 'viewed_homepage');
Context::push('user_actions', 'added_to_cart');
// Later in your code
$actions = Context::get('user_actions');
// ['viewed_homepage', 'added_to_cart']
3. Scoped Context
Temporarily change context for a specific block of code:
Context::add('color', 'blue');
Context::scope(function () {
Context::add('color', 'red');
echo Context::get('color'); // Outputs: red
}, ['temp' => 'value']);
echo Context::get('color'); // Outputs: blue
echo Context::get('temp'); // Outputs: null (scoped data is gone)
Context with Queued Jobs
One of the most powerful features is how context works with queued jobs:
// In your controller
Context::add('source', 'web_checkout');
ProcessOrder::dispatch($order);
// In your job
class ProcessOrder implements ShouldQueue
{
public function handle()
{
Log::info('Processing order');
// Log will include: {"source":"web_checkout"}
}
}
Practical Use Cases
1. Debugging Distributed Systems
// At start of request
Context::add('trace_id', Str::uuid());
// This ID will follow through:
// - Database queries
// - API calls
// - Queue jobs
// - Log entries
2. Performance Monitoring
DB::listen(function ($query) {
Context::push('queries', [
'sql' => $query->sql,
'time' => $query->time
]);
});
// Later see all queries executed
$queries = Context::get('queries');
3. User Journey Tracking
// Middleware
Context::push('user_journey', 'landed_on:'.$request->path());
// Controller after login
Context::push('user_journey', 'authenticated');
// After purchase
Context::push('user_journey', 'purchased:'.$product->id);
// See complete journey
$journey = Context::get('user_journey');
Best Practices
- Be mindful of size: Don't store large amounts of data in context
- Use hidden context for sensitive information
- Clear unused data with
Context::forget() - Use descriptive keys for easy understanding
- Combine with logging for powerful debugging
Conclusion
Laravel's Context feature is like giving your application a memory that travels with each request and job. It helps you:
- Track user journeys
- Debug complex flows
- Maintain consistency across distributed operations
- Add rich metadata to logs
By using Context effectively, you can build more observable, maintainable applications with better debugging capabilities.
Remember, context is your friend when you need to understand the "story" behind what's happening in your application!
Projects related to this guide
Use the concepts from this article in practical source-code projects.
Flask Authentication System (Free Version) - Kritim Yantra
🛠 Features✔ Google & GitHub Authentication✔ User Registration & Login✔ Profile/Dashboard Access✔ Secure...
Python Flask Blog Project with Admin Panel
Are you ready to launch a powerful, modern, and fully customizable blog? Look no further! Introducing the Flask-...
Laravel 12 + ReactJS Starter Kit: Add Multi-Language Support (Arabic, English, Spanish) with Blog CRUD
🚀 Installation & Setup Download & Extract Get the ZIP from kritimyantra.com and extract it. Includes pr...
Comments
No comments yet. Be the first to comment.
Sign in to join the discussion.