← BACK
Laravel / Collections

Transform Non-Empty Datasets Fluently with whenNotEmpty()

Punyapal Shah • • 1 min read
edit this tip →

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 if statements.

Related Tips

View all tips →
Laravel Collections

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.

READ >

// Got a tip in mind? Contributions are always welcome