Conditional Context Management Made Easy with Laravel's Context Facade
Last updated on by Harris Raftopoulos

Manage contextual data more elegantly with Laravel's Context Facade now equipped with the Conditionable trait. This powerful combination allows for expressive conditional logic when sharing data across your application.
Context::when( auth()->user()->isAdmin(), fn ($context) => $context->add('user', ['key' => 'other data', ...auth()->user()]), fn ($context) => $context->add('user', auth()->user()),);
The code above demonstrates how to conditionally add different user data to your context based on admin status, creating a more streamlined approach to context-specific behavior.
// Add different feature flags based on environmentContext::when( app()->environment('production'), fn ($context) => $context->add('features', ['beta' => false]), fn ($context) => $context->add('features', ['beta' => true])); // Add user permissions based on roleContext::when( auth()->user()->isAdmin(), fn ($context) => $context->add('permissions', 'all'), fn ($context) => $context->add('permissions', 'limited'));
With methods like when
and unless
, your context management becomes more readable and maintainable. This approach is especially valuable when setting up role-based configurations, environment-specific settings, or feature flags throughout your application. By consolidating conditional logic directly into your context management, you reduce scattered if/else statements and create more coherent, self-documenting code.