PHP
Building Dynamic Eloquent Queries with Conditional `when()`
Enhance your Laravel Eloquent queries by adding conditional clauses dynamically using the `when()` method, improving readability and maintainability.
<?php
namespace App\Http\Controllers;
use App\Models\Order;
use Illuminate\Http\Request;
use Illuminate\Support\Carbon;
class OrderController extends Controller
{
public function index(Request $request)
{
$status = $request->input('status');
$search = $request->input('search');
$startDate = $request->input('start_date');
$endDate = $request->input('end_date');
$minTotal = $request->input('min_total');
$orders = Order::query()
->when($status, function ($query, $status) {
return $query->where('status', $status);
})
->when($search, function ($query, $search) {
return $query->where('order_number', 'like', '%' . $search . '%')
->orWhere('customer_name', 'like', '%' . $search . '%');
})
->when($startDate, function ($query, $startDate) {
return $query->whereDate('created_at', '>=', Carbon::parse($startDate));
})
->when($endDate, function ($query, $endDate) {
return $query->whereDate('created_at', '<=', Carbon::parse($endDate));
})
->when($minTotal, function ($query, $minTotal) {
return $query->where('total_amount', '>=', $minTotal);
})
->orderBy('created_at', 'desc')
->paginate(15);
return view('orders.index', compact('orders'));
}
}
How it works: The `when()` method allows you to apply conditional clauses to your Eloquent queries, making them more dynamic and readable. It takes two arguments: a boolean condition and a closure. If the condition is true, the closure is executed, receiving the query builder instance and the conditional value as arguments, allowing you to add `where`, `orderBy`, or other clauses. This is incredibly useful for building search and filter functionalities based on user input without repetitive `if` statements.