Safely Override Context Data in Laravel Using Context::scope()
The Problem: Temporary Data Overrides
In Laravel, Context is great for sharing request-level data like:
- request IDs
- order IDs
- user info
But what if you need to temporarily override some values?
If not handled properly, you may:
- overwrite global context
- leak wrong data into logs
- break tracing/debugging
Real Project Example: Order Processing Logs
use Illuminate\Support\Facades\Context;
use Illuminate\Support\Facades\Log;
// Global request context
Context::add('request_id', 'REQ-101');
Context::addHidden('admin_id', 10);
Context::scope(
function () {
Context::add('process', 'order_payment');
$adminId = Context::getHidden('admin_id');
Log::info("Processing payment approved by admin {$adminId}");
// Logs include:// request_id, process
},
data: ['order_id' => 'ORD-9001'],
hidden: ['admin_id' => 99],
);
After Scope Execution
Context::all();
// ['request_id' => 'REQ-101']
Context::allHidden();
// ['admin_id' => 10]
Everything is restored automatically.