Create AWESOME code snippets and share them with the world in seconds!

X

Laravel Tip: Use The `When()` Helper For Clean Conditional Logic

Published on June 8, 2025 by

Laravel Tip: Use the `when()` Helper for Clean Conditional Logic

Laravel when() helper is a powerful tool for writing clean and concise conditional logic—especially useful in Blade templates, service definitions, and route declarations.

🧠 What is when()?

The when() function returns the value it’s given only if a condition is true. If the condition is false, it returns null. You can pass a value or a closure as the second argument.

$value = when(true, 'Hello World');
// "Hello World"
 
$value = when(false, 'Hello World');
// null
 
$value = when(true, fn () => 'Hello World');
// "Hello World"

✨ Real-World Use Cases

📧 Local Email Previews

Register test routes only in local environments:

<?php
use Illuminate\Support\Facades\App;
use Illuminate\Support\Facades\Route;
use App\Mail\WelcomeMail;
 
when(App::isLocal(), function () {
Route::get('/email/preview/welcome', function () {
return new \App\Mail\WelcomeMail(auth()->user());
})->middleware('auth');
});

🛠 Pro Tips

you can use when() to service configuration or chained builders

$builder->when($isAdmin, function ($query) {
$query->with('adminData');
});

Dinesh Uprety

Senior Software Engineer • Writer @ Laranepal • PHP, Laravel, Livewire, TailwindCSS & VueJS • CEO @ Laranepal & Founder @ laracodesnap

Filed in:

Discussion

Login or register to comment or ask questions

No comments or questions yet...

SPONSORED
Codesnap

Codesnap

Create AWESOME code snippets and share them with the world in seconds!