Context Data Filtering with Laravel's New except() Methods

Context data filtering gets more convenient with Laravel's new except() and exceptHidden() methods, allowing you to retrieve all context except specified keys.
When working with Laravel's Context service, you often need to share context data while excluding sensitive or irrelevant information. The new filtering methods provide a clean way to retrieve context data with specific keys omitted, making it safer to log or transmit context information.
Let's see how it works:
Context::add('user_id', 42);
Context::add('request_id', 'req-abc123');
Context::add('ip_address', '192.168.0.1');
Context::addHidden('sensitive_token', 'secret');
// Get all context except specified keys
$logData = Context::except(['sensitive_token']);
// Result:
[
'user_id' => 42,
'request_id' => 'req-abc123',
'ip_address' => '192.168.0.1',
]
// Filter hidden context
$filtered = Context::exceptHidden(['sensitive_token']);
Real-World Example
Here's how you might use these methods in a logging service:
class AuditLogger
{
public function logUserAction(string $action, array $details = [])
{
$contextData = Context::except([
'password',
'api_key',
'session_token'
]);
Log::info('User action performed', [
'action' => $action,
'details' => $details,
'context' => $contextData,
'timestamp' => now()
]);
}
public function generateReport()
{
return [
'request_context' => Context::except([
'sensitive_data',
'internal_flags'
]),
'system_info' => Context::exceptHidden([
'debug_tokens',
'internal_keys'
])
];
}
}
These filtering methods make it safer to work with context data by providing explicit control over what information gets included in logs, reports, or external communications.
Stay Updated with More Laravel Tips
Enjoyed this article? There's plenty more where that came from! Subscribe to our channels to stay updated with the latest Laravel tips, tricks, and best practices:
- Follow us on Twitter @harrisrafto
- Join us on Bluesky @harrisrafto.eu
- Subscribe to our YouTube channel harrisrafto