Laravel 8 whenEmpty() {#collection-method}
whenEmpty
方法是当集合为空时,将执行给定的回调函数:
$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']
$collection = collect(['michael', 'tom']);
$collection->whenEmpty(function ($collection) {
return $collection->push('adam');
}, function ($collection) {
return $collection->push('taylor');
});
$collection->all();
// ['michael', 'tom', 'taylor']
与 whenEmpty
相反的方法,请查看 whenNotEmpty
方法。