PHP
Building Dynamic Eloquent Queries with the `when()` Method
Learn to construct flexible and dynamic Laravel Eloquent queries using the `when()` method, allowing you to conditionally apply query constraints based on specific conditions.
use App\Models\Product;
use Illuminate\Http\Request;
class ProductController extends Controller
{
public function index(Request $request)
{
$search = $request->input('search');
$minPrice = $request->input('min_price');
$category = $request->input('category');
$products = Product::query()
->when($search, function ($query, $search) {
return $query->where('name', 'like', '%'.$search.'%')
->orWhere('description', 'like', '%'.$search.'%');
})
->when($minPrice, function ($query, $minPrice) {
return $query->where('price', '>=', $minPrice);
})
->when($category, function ($query, $category) {
return $query->where('category_id', $category);
})
->orderBy('name')
->get();
return view('products.index', compact('products'));
}
}
How it works: The `when()` method provides a clean and fluent way to conditionally apply query clauses to an Eloquent builder. It accepts a boolean as its first argument (the condition) and a callback function as its second. If the condition is true, the callback is executed, receiving the query builder instance and the condition's value (if not null). This eliminates the need for verbose `if` statements, resulting in more readable and maintainable dynamic queries, especially useful for filtering results based on user input.