Use when() and unless() on query builders to apply conditional clauses without breaking method chains with if statements.
Building dynamic search queries often breaks method chains with if ($search) { $query->where(...) }. The when() and unless() methods evaluate conditions inline within query chains.
use App\Models\User;
$users = User::query()
->when($request->search, fn ($q, $search) => $q->where('name', 'like', "%{$search}%"))
->unless($request->include_archived, fn ($q) => $q->whereNull('archived_at'))
->get();
- Keeps query builder method chains fluent without breaking into if statements
- when() executes closure if first parameter evaluates to truthy
- unless() executes closure if first parameter evaluates to falsey
Related Tips
View all tips →Refresh and Pessimistically Lock Models with refreshForUpdate() in Laravel 13.27
Laravel 13.27 adds refreshForUpdate(), reloading an existing model instance in-place with fresh database attributes while acquiring an exclusive FOR UPDATE row lock.
Scope Pivot Table Queries with Closures in wherePivot() in Laravel 13.26
Laravel 13.26 allows wherePivot() and orWherePivot() to accept closures, enabling direct reuse of local scopes defined on custom Pivot models.