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 →
Agent Run Observability in Laravel AI SDK 0.11 image

Agent Run Observability in Laravel AI SDK 0.11

Read article
Debounced Queued Event Listeners in Laravel image

Debounced Queued Event Listeners in Laravel

Read article
Statamic Mailables Viewer Previews Laravel Emails in the Control Panel image

Statamic Mailables Viewer Previews Laravel Emails in the Control Panel

Read article
Laravel Tackle: Run an AI Coding Agent in Your Laravel App image

Laravel Tackle: Run an AI Coding Agent in Your Laravel App

Read article
Queue::forward(): Reroute Laravel Queues in One Place image

Queue::forward(): Reroute Laravel Queues in One Place

Read article
Laravel Read-Through Filesystem: Lazy Storage Migration image

Laravel Read-Through Filesystem: Lazy Storage Migration

Read article