Vivek Mistry 👋

I’m a Certified Senior Laravel Developer with 8+ years of experience , specializing in building robust APIs and admin panels, frontend templates converting them into fully functional web applications.

Book A Call
  • 27 Feb, 2026
  • 15 Views
  • Write smarter, more expressive conditional queries beyond basic filtering.

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: