php 46 lines · 7 steps

Conditional query building in Laravel

Eloquent's when() lets you assemble a filtered, sorted, paginated query from optional request parameters without a tangle of if statements.

Explained by highlit
1<?php
2 
3namespace App\Http\Controllers;
4 
5use App\Models\Product;
6use Illuminate\Http\Request;
7 
8class ProductController extends Controller
9{
10 public function index(Request $request)
11 {
12 $products = Product::query()
13 ->when($request->filled('search'), function ($query) use ($request) {
14 $term = $request->string('search');
15 
16 $query->where(function ($query) use ($term) {
17 $query->where('name', 'like', "%{$term}%")
18 ->orWhere('sku', 'like', "%{$term}%");
19 });
20 })
21 ->when($request->integer('category_id'), function ($query, $categoryId) {
22 $query->where('category_id', $categoryId);
23 })
24 ->when($request->filled('min_price'), function ($query) use ($request) {
25 $query->where('price', '>=', $request->float('min_price'));
26 })
27 ->when($request->filled('max_price'), function ($query) use ($request) {
28 $query->where('price', '<=', $request->float('max_price'));
29 })
30 ->when($request->boolean('in_stock'), function ($query) {
31 $query->where('stock', '>', 0);
32 })
33 ->when(
34 $request->input('sort'),
35 fn ($query, $sort) => $query->orderBy(
36 ltrim($sort, '-'),
37 str_starts_with($sort, '-') ? 'desc' : 'asc'
38 ),
39 fn ($query) => $query->latest()
40 )
41 ->paginate($request->integer('per_page', 15))
42 ->withQueryString();
43 
44 return response()->json($products);
45 }
46}
01 / 01
STEP 01

Walkthrough

Space play step click any line
Three takeaways
  1. 1when() applies a clause only when its condition is truthy, keeping conditional query logic flat and readable.
  2. 2Request accessors like string(), integer(), and boolean() coerce raw input into safe, typed values at the point of use.
  3. 3Grouping OR conditions inside a nested closure prevents them from leaking out and breaking sibling AND filters.

Related explainers

Share this explainer

Here's the card — post it anywhere.

Conditional query building in Laravel — share card
Made with highlit — turn any snippet into a walkthrough like this in about a minute.
Explain your code