PHP

Dynamic Conditional Query Filtering

Master dynamic query filtering in Eloquent using the `when` method to conditionally apply clauses based on input, making your Laravel queries more flexible and readable.

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

// Assume $request is an instance of Illuminate\Http\Request
// E.g., from a controller method: public function index(Request $request)

$posts = Post::query()
    ->when($request->has('category_id'), function ($query) use ($request) {
        $query->where('category_id', $request->input('category_id'));
    })
    ->when($request->filled('status'), function ($query) use ($request) {
        $query->where('status', $request->input('status'));
    })
    ->when($request->boolean('is_published'), function ($query) {
        $query->where('is_published', true);
    })
    ->orderBy('created_at', 'desc')
    ->get();
How it works: The `when` method allows you to apply query clauses conditionally. It takes a boolean value (or a closure that returns a boolean) as its first argument. If the condition is true, the second argument (a closure) is executed, allowing you to add `where` clauses, `orderBy` clauses, or any other query builder methods. If the condition is false, the closure is skipped. This significantly cleans up your code by avoiding multiple `if` statements for optional query parameters, making your query building more fluent and readable.

Need help integrating this into your project?

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

Hire DigitalCodeLabs