📖 1 minute read
Laravel collections provide whenNotEmpty() and whenEmpty() methods for conditional logic execution, which is cleaner than manual empty checks.
Before (verbose):
if (!$order->items->isEmpty()) {
$order->items->each(fn($item) => $item->ship());
}
After (fluent):
$order->items->whenNotEmpty(function ($items) {
$items->each(fn($item) => $item->ship());
});
Bonus—both branches:
$user->notifications
->whenNotEmpty(fn($notifications) => $this->send($notifications))
->whenEmpty(fn() => Log::info('No notifications to send'));
This pattern keeps your code fluent and avoids breaking the collection chain. The closure receives the collection as a parameter, so you don’t need to reference the original variable again.
Leave a Reply