Advanced when() Patterns in Laravel You Probably Don’t Use

Write smarter, more expressive conditional queries beyond basic filtering.

  • 27 Feb, 2026
  • 341 Views

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 sort exists → order by price
  • If not → apply default sorting

This replaces:

if ($request->sort) {
   ...
} else {
   ...
}

Cleaner and fully chained.

Share: