Laravel - Collections - Method Whennotempty

The whenNotEmpty method will execute the given callback when the collection is not empty:

    
    $collection = collect(['michael', 'tom']);
    
    $collection->whenNotEmpty(function ($collection) {
        return $collection->push('adam');
    });
    
    $collection->all();
    
    // ['michael', 'tom', 'adam']
    
    $collection = collect();
    
    $collection->whenNotEmpty(function ($collection) {
        return $collection->push('adam');
    });
    
    $collection->all();
    
    // []
	

A second closure may be passed to the whenNotEmpty method that will be executed when the collection is empty:

    
    $collection = collect();
    
    $collection->whenNotEmpty(function ($collection) {
        return $collection->push('adam');
    }, function ($collection) {
        return $collection->push('taylor');
    });
    
    $collection->all();
    
    // ['taylor']
	

For the inverse of whenNotEmpty, see the whenEmpty method.