Laravel's Eloquent provides a powerful when() method for building conditional queries. Instead of verbose if-else blocks, you can elegantly add conditions to queries, resulting in more readable and maintainable code.
Example
$query = User::query()
->when($isActive, fn($q) => $q->where('active', true))
->when($role, fn($q) => $q->where('role', $role))
->get();
With this approach, conditions are only added if $isActive or $role are truthy, ensuring that queries remain DRY and concise.
💡 Benefits
- Repetitive code is reduced.
- Readability is enhanced.
- Complex queries become simpler to manage.
- The when() method serves as an effective tool for cleaner Eloquent queries.