What is the when() method in Laravel Query Builder?
Why Interviewers Ask This
Candidates at the intermediate level are expected to not only know this concept but explain the trade-offs involved. Interviewers use this question to see if you can reason about design decisions, not just recall facts.
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.
Pro Tip
Back up your answer with a specific project or situation. Saying 'In my last Laravel project, I used this when...' immediately makes your answer more credible and memorable.