Laravel Tutorials

Conditional Context Management Made Easy with Laravel's Context Facade

Published
Conditional Context Management Made Easy with Laravel's Context Facade image

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 environment
Context::when(
app()->environment('production'),
fn ($context) => $context->add('features', ['beta' => false]),
fn ($context) => $context->add('features', ['beta' => true])
);
 
// Add user permissions based on role
Context::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.

Harris Raftopoulos photo

Senior Software Engineer • Staff & Educator @ Laravel News • Co-organizer @ Laravel Greece Meetup

Sponsored

laravelcloud logo
Laravel Cloud

Easily create and manage your servers and deploy your Laravel applications in seconds.

Visit Laravel Cloud

The latest

View all →
PayZephyr: One Payment API for Stripe, Paystack, and PayPal image

PayZephyr: One Payment API for Stripe, Paystack, and PayPal

Read article
Bifrost Turns One With AI Builds and New Workflows image

Bifrost Turns One With AI Builds and New Workflows

Read article
Preview Blade Templates in macOS Finder with Quick Blade image

Preview Blade Templates in macOS Finder with Quick Blade

Read article
Artisan Debugging Commands in Laravel Telescope 5.24.0 image

Artisan Debugging Commands in Laravel Telescope 5.24.0

Read article
Queue totalSize() and JobInterrupted Event in Laravel 13.31 image

Queue totalSize() and JobInterrupted Event in Laravel 13.31

Read article
Find Unexpected Test Inputs with Fuzz for Pest image

Find Unexpected Test Inputs with Fuzz for Pest

Read article