🔴 Laravel Intermediate

What is the when() method in Laravel Query Builder?

Answer

The when() method applies a query clause conditionally, only when a given value is truthy. This avoids messy if-else blocks when building dynamic queries. Example: $query = User::query(); $query->when($request->name, fn($q, $name) => $q->where("name", "like", "%$name%"))->when($request->role, fn($q, $role) => $q->where("role", $role))->when($request->active, fn($q) => $q->where("active", true)). The callback receives the query builder and the value. If the value is falsy (null, false, 0, empty string), the callback is skipped entirely. You can also provide an "else" callback as the third argument: ->when($isAdmin, fn($q) => $q->withTrashed(), fn($q) => $q->where("active", true)). This pattern keeps dynamic query building clean and readable without if-statements scattered through the code.