← Back to all snippets
PHP

Building Conditional Queries with Eloquent's when() Method

Dynamically build Laravel Eloquent queries based on specific conditions using the `when()` method, making your query logic cleaner, more readable, and highly flexible.

use App\Models\Product;
use Illuminate\Http\Request;

// Simulate a request object
$request = new Request(['category' => 'electronics', 'price_min' => 100]);

$products = Product::when($request->has('category'), function ($query) use ($request) {
        $query->where('category', $request->category);
    })
    ->when($request->has('price_min'), function ($query) use ($request) {
        $query->where('price', '>=', $request->price_min);
    })
    ->when($request->has('price_max'), function ($query) use ($request) {
        $query->where('price', '<=', $request->price_max);
    })
    ->get();

// To view the generated SQL (for debugging)
// dd($products->toSql());
How it works: The `when()` method allows you to apply query constraints conditionally. It accepts two arguments: a boolean value and a closure. If the boolean is `true`, the closure is executed, and you can apply your query logic within it. This is incredibly useful for building dynamic filters based on user input (e.g., from a request) or other changing conditions, leading to more organized and less repetitive query code.

Need help integrating this into your project?

Our team of expert developers can help you build your custom application from scratch.

Hire DigitalCodeLabs