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 →
CPX: The Composer Package Executor for PHP image

CPX: The Composer Package Executor for PHP

Read article
Laravel AI SDK Adds Human-in-the-Loop Tool Approval image

Laravel AI SDK Adds Human-in-the-Loop Tool Approval

Read article
Pest 5 Released With Test Impact Analysis, Agent Verification, and Evals image

Pest 5 Released With Test Impact Analysis, Agent Verification, and Evals

Read article
Queue-SQL: Run Mass Deletes and Updates Across Parallel Queue Jobs image

Queue-SQL: Run Mass Deletes and Updates Across Parallel Queue Jobs

Read article
Blade Formatting in Laravel Pint image

Blade Formatting in Laravel Pint

Read article
Inertia DevTools Is Now on the Chrome Web Store image

Inertia DevTools Is Now on the Chrome Web Store

Read article