Could we help you? Please click the banners. We are young and desperately need the money
Writing dynamic queries in Laravel often means dealing with complex conditional logic. Developers frequently use verbose if statements outside the query builder to conditionally apply filters or joins. Laravel’s elegant when() and unless() helpers provide a fluent, expressive way to write cleaner and more maintainable query logic directly within the builder chain.
In this guide, we’ll break down how these helpers work, their benefits, and how to apply them in real-world scenarios — all while keeping your code elegant and DRY.
Instead of writing something like:
if (request('active')) { $users = User::where('is_active', true)->get(); } else { $users = User::get(); }
You can write:
$users = User::when(request('active'), function ($query) { return $query->where('is_active', true); })->get();
$users = User::when(request('status'), function ($query, $status) { return $query->where('status', $status); })->get();
If request('status') is null, no where condition is applied.
$posts = Post::when(request('sort_by') === 'popular', function ($query) { return $query->orderByDesc('views'); })->get();
You can even combine with unless() for inverse logic:
$posts = Post::unless(request('archived'), function ($query) { return $query->where('is_archived', false); })->get();
$orders = Order::query() ->when(request('with_customer'), function ($query) { return $query->with('customer'); }) ->get();
$products = Product::query() ->when(request('category'), fn ($q, $cat) => $q->where('category_id', $cat)) ->when(request('search'), fn ($q, $term) => $q->where('name', 'like', "%$term%")) ->get();
This replaces multiple nested if statements while remaining readable.
You can use when()/unless() in jobs, seeders, or console commands to build logic-driven queries based on flags or arguments.
$flag = $this->option('only-active'); User::when($flag, function ($query) { $query->where('is_active', true); })->chunk(100, function ($users) { // Process });
Laravel’s when() and unless() methods help you write smarter, cleaner queries without losing readability. By keeping your conditional logic fluent, you make your code easier to test, maintain, and expand.
If you find yourself writing too many if blocks around query logic — it’s time to refactor with these elegant helpers.