Laravel - Collections - Method Whenempty

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

    
    $collection = collect(['Michael', 'Tom']);
    
    $collection->whenEmpty(function ($collection) {
        return $collection->push('Adam');
    });
    
    $collection->all();
    
    // ['Michael', 'Tom']
    
    $collection = collect();
    
    $collection->whenEmpty(function ($collection) {
        return $collection->push('Adam');
    });
    
    $collection->all();
    
    // ['Adam']
	

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

    
    $collection = collect(['Michael', 'Tom']);
    
    $collection->whenEmpty(function ($collection) {
        return $collection->push('Adam');
    }, function ($collection) {
        return $collection->push('Taylor');
    });
    
    $collection->all();
    
    // ['Michael', 'Tom', 'Taylor']
	

For the inverse of whenEmpty, see the whenNotEmpty method.