Laravel Tip: Use The `When()` Helper For Clean Conditional Logic
Published on June 8, 2025 by Dinesh Uprety

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:
<?phpuse 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');});

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