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

By Dinesh Uprety
Published: 2025-06-07
Updated: 2025-06-08
Canonical: https://laranepal.com/blog/laravel-tip-use-the-when-helper-for-clean-conditional-logic

[Laravel `when()`](https://laravel.com/docs/11.x/helpers#method-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.

```php
$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
<?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

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