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
‹ swipe to step through ›
Walkthrough
Space play
←→ step
click any line
Three takeaways
- 1when() applies a clause only when its condition is truthy, keeping conditional query logic flat and readable.
- 2Request accessors like string(), integer(), and boolean() coerce raw input into safe, typed values at the point of use.
- 3Grouping OR conditions inside a nested closure prevents them from leaking out and breaking sibling AND filters.
Related explainers
php
<?php class NameParser {
Parsing a full name into components in PHP
string-parsing
arrays
normalization
Intermediate
8 steps
php
<?php namespace App\Services\Checkout;
Validating coupons with Laravel's Pipeline
pipeline
chain of responsibility
transactions
Intermediate
7 steps
javascript
function evaluate(expression) { const tokens = tokenize(expression); let pos = 0;
Building a recursive descent calculator
parsing
recursion
operator-precedence
Intermediate
8 steps
php
<?php namespace App\Services;
How a password strength validator works in PHP
validation
regular-expressions
data-driven
Intermediate
8 steps
php
<?php namespace App\Services;
Building a cached daily leaderboard in Laravel
caching
aggregation
eager-loading
Intermediate
9 steps
php
<?php final class RotatingFileLogger {
How a rotating file logger works in PHP
logging
file-rotation
io
Intermediate
9 steps
Share this explainer
Here's the card — post it anywhere.
Made with highlit — turn any snippet into a walkthrough like this in about a minute.
Explain your code
Embed this explainer
Drop the interactive walkthrough into a blog or docs. Views never cost a credit.
<iframe src="https://highlit.co/explainers/conditional-query-building-in-laravel-explained-php-6193/embed?autoplay=1" width="100%" height="520" loading="lazy" style="border:0"></iframe>
Autoplay is on by default — add ?autoplay=0 to start paused.