Vivek Mistry 👋

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

Book A Call
  • 05 Jun, 2025
  • 162 Views
  • Laravel Tip: Use when() for Cleaner Queries

Use when() for Cleaner Queries

Writing conditional queries in Laravel often gets messy with if statements. Luckily, Laravel gives us a neat helper: when().

Instead of this:

$query = User::query();
if (request('role')) {
    $query->where('role', request('role'));
}
if (request('active')) {
    $query->where('active', true);
}
$users = $query->get();

You can write this:

$users = User::query()
    ->when(request('role'), fn($q, $role) => $q->where('role', $role))
    ->when(request('active'), fn($q) => $q->where('active', true))
    ->get();

✅ Cleaner

✅ More readable

✅ No repeated if blocks

Share: