Advanced when() Patterns in Laravel You Probably Don’t Use
Using the Third Parameter (Default Callback)
Many developers don’t know when() has a third argument.
->when(
$request->sort,
fn ($q) => $q->orderBy('price'),
fn ($q) => $q->orderBy('created_at', 'desc')
)
What Happens?
- If
sortexists → order by price - If not → apply default sorting
This replaces:
if ($request->sort) {
...
} else {
...
}
Cleaner and fully chained.