Use whenNotEmpty() on Laravel Collections to execute transformations or side effects only when collections contain items.
When transforming collections or sending batch notifications, wrapping collection pipelines in external if ($collection->isNotEmpty()) blocks interrupts fluent method chaining.
whenNotEmpty() runs the given closure only if the collection contains one or more items.
Basic Usage
$pendingInvoices = Invoice::where('status', 'pending')->get();
$pendingInvoices
->whenNotEmpty(function ($invoices) {
// Runs only if there is at least 1 invoice
Notification::send(User::getFinanceTeam(), new BatchInvoiceAlert($invoices));
})
->whenEmpty(function () {
logger()->info('No pending invoices found for processing.');
});
Transforming Items Fluently
$users = collect($rawUsers)
->whenNotEmpty(function ($collection) {
return $collection->sortBy('created_at')->values();
});
Summary
- Executes closure only if
$collection->count() > 0. - Complements
whenEmpty()for complete conditional pipeline flows. - Maintains fluent chaining without external
ifstatements.
Related Tips
View all tips →Simplify Collection Operations with Higher-Order Messages
Laravel Collections support higher-order messages through dynamic properties, allowing operations like each, map, filter, and groupBy to work directly with an item's property or method without writing boilerplate callbacks.
Generate Iterative Collections Quickly with Collection::times()
Use Collection::times() to generate numeric-sequence collections or execute closures N times fluently without writing for loops.