PHP
Dynamically Building Queries with Eloquent's `when()` Method
Master Laravel Eloquent's `when()` method to conditionally add query clauses, creating highly flexible and dynamic queries based on specific application conditions or user input.
<?php
namespace App\Http\Controllers;
use App\Models\Product;
use Illuminate\Http\Request;
class ProductController extends Controller
{
public function index(Request $request)
{
$category = $request->input('category');
$minPrice = $request->input('min_price');
$isAvailable = $request->boolean('available');
$products = Product::query()
->when($category, function ($query, $category) {
return $query->where('category', $category);
})
->when($minPrice, function ($query, $minPrice) {
return $query->where('price', '>=', $minPrice);
})
->when($isAvailable, function ($query) {
// Only add this clause if $isAvailable is true
return $query->where('stock', '>', 0);
})
->when($request->has('search'), function ($query) use ($request) {
// Use another request parameter if 'search' exists
$searchTerm = '%' . $request->input('search') . '%';
return $query->where('name', 'like', $searchTerm)
->orWhere('description', 'like', $searchTerm);
})
->orderBy('created_at', 'desc')
->get();
return response()->json($products);
}
}
How it works: The `when()` method in Laravel Eloquent is a powerful tool for building conditional queries. It takes two arguments: a boolean condition and a closure. If the condition evaluates to `true`, the closure is executed, and its return value is used to continue building the query. If `false`, the query builder simply proceeds without executing the closure. This allows you to easily include or exclude query clauses based on dynamic factors like user input, environment settings, or other runtime conditions, resulting in much cleaner and more readable conditional logic compared to traditional `if` statements.