PHP
Building Dynamic Queries with Laravel Eloquent's `when()` Method
Master the `when()` method in Laravel Eloquent to conditionally apply query clauses, simplifying complex dynamic query construction and improving code readability.
use App\Models\Book;
$searchTerm = request('search');
$categoryId = request('category');
$sortBy = request('sort_by', 'created_at');
$sortOrder = request('sort_order', 'desc');
$books = Book::query()
->when($searchTerm, function ($query, $searchTerm) {
$query->where('title', 'like', '%' . $searchTerm . '%')
->orWhere('author', 'like', '%' . $searchTerm . '%');
})
->when($categoryId, function ($query, $categoryId) {
$query->where('category_id', $categoryId);
})
->when($sortBy, function ($query, $sortBy) use ($sortOrder) {
$query->orderBy($sortBy, $sortOrder);
}, function ($query) {
// Default order if $sortBy is not provided
$query->orderBy('title', 'asc');
})
->get();
foreach ($books as $book) {
echo "Book: " . $book->title . " by " . $book->author . "
";
}
How it works: The `when()` method in Laravel Eloquent is a powerful tool for constructing dynamic queries based on conditional logic. It takes a boolean condition as its first argument and a closure as its second. If the condition is true, the closure is executed, allowing you to apply query clauses. An optional third closure can be provided to execute if the condition is false. This greatly cleans up conditional statements in query builders, making your code more expressive and less verbose, especially when dealing with optional search filters or sorting parameters.