When To Use Laravel When
In Laravel, the when method is a versatile and elegant way to conditionally execute logic within your code. It simplifies conditional operations, improving readability and reducing clutter, particularly in chained methods or query builders.
Here’s a breakdown of when to use when in Laravel:
1. Conditional Query Building
The when method is often used to add conditions to query builders dynamically based on certain criteria.
Example: Applying a Filter Dynamically
$query = User::query();
$users = $query->when(request('role'), function ($q, $role) {
$q->where('role', $role);
})->get();
? Why Use when Here?
? If request('role') exists, the condition is applied.
? If request('role') is null, the condition is skipped, keeping the code clean and concise.
2. Conditional Logic in Collections
The when method can also be used in collections to perform operations based on certain conditions.
Example: Transforming Data Conditionally
$collection = collect([1, 2, 3, 4]);
$result = $collection->when(true, function ($coll) {
return $coll->map(fn ($item) => $item * 2);
});
? Why Use when Here?
? It allows conditional execution without needing separate if statements, making the code more readable.
3. Cleaner Code in Controllers
The when method can simplify controller logic by removing multiple nested if statements.
Example: Conditionally Adding Features
$data = [];
$data = collect($data)->when($user->isAdmin(), function ($data) {
return $data->put('admin_tools', true);
})->when($user->isPremium(), function ($data) {
return $data->put('premium_features', true);
});
? Why Use when Here?
? Avoids deeply nested conditions.
领英推荐
? Keeps the logic declarative and easier to follow.
4. Improving Readability in Fluent Chains
When working with methods that are chained together, when can help conditionally apply parts of the chain without breaking the flow.
Example: Fluent Chain with Conditional Middleware
Route::get('/dashboard', [DashboardController::class, 'index'])->when(auth()->user()->isAdmin(), fn ($route) => $route->middleware('admin'));
? Why Use when Here?
? Maintains a fluent interface while conditionally applying middleware.
5. In Custom Logic or Helper Functions
You can use when to conditionally execute logic in helper functions, avoiding explicit if statements.
Example: Simplifying a Helper Function
function formatPrice($price, $applyDiscount = false) {
return collect(['price' => $price])
->when($applyDiscount, function ($data) {
$data['price'] *= 0.9; // Apply 10% discount
})->get('price');
}
? Why Use when Here?
? Keeps the function logic compact and readable.
Conclusion
Use Laravel’s when method whenever you need to conditionally execute logic without breaking the flow of your code. It is particularly useful in:
? Query builders.
? Collections.
? Fluent chains.
? Replacing nested if statements for better readability.
By leveraging when, you can write cleaner, more expressive Laravel applications that are easier to maintain.