Conditional Logic with Collection whenNotEmpty

📖 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.

Daryle De Silva

VP of Technology

11+ years building and scaling web applications. Writing about what I learn in the trenches.

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *