Menü schliessen
Created: April 30th 2025
Categories: IT Development,  Laravel
Author: Nikola Jevtic

Write Cleaner Eloquent Queries with Laravel’s when() and unless() Helpers

Donation Section: Background
Monero Badge: QR-Code
Monero Badge: Logo Icon Donate with Monero Badge: Logo Text
82uymVXLkvVbB4c4JpTd1tYm1yj1cKPKR2wqmw3XF8YXKTmY7JrTriP4pVwp2EJYBnCFdXhLq4zfFA6ic7VAWCFX5wfQbCC

Introduction

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.


Why Use when() and unless() in Laravel?

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();

Benefits:

  • Cleaner, chainable logic
  • No need to break the query builder chain
  • Supports ternary-like readability
  • Easy to read, test, and refactor

Real-World Use Cases

1. Filter Users Based on Status

$users = User::when(request('status'), function ($query, $status) {
    return $query->where('status', $status);
})->get();

If request('status') is null, no where condition is applied.


2. Apply Sorting Only When Requested

$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();

3. Conditionally Add Joins or Relationships

$orders = Order::query()
    ->when(request('with_customer'), function ($query) {
        return $query->with('customer');
    })
    ->get();

4. Build Search Queries Dynamically

$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.


Use in Console Commands or Jobs

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
});

Conclusion

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.