Laravel Tip: Eloquent's 'when' Method for Cleaner Conditional Queries

Published: Aug 21, 2025, 12:21 AM (BD Time) Updated: Aug 21, 2025, 12:21 AM (BD Time)

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