How to Remove Null Values From a Collection in Laravel
Arie Visser • May 25, 2021
laravel phpSometimes, you may end up with a collection that contains null
values.
Removing those null
values from the collection can be done very smoothly with the filter
method.
When you look at the source code of the filter
method in the Illuminate\Support\Collection
class, you will see that $callback
is an optional parameter:
public function filter(callable $callback = null)
{
if ($callback) {
return new static(Arr::where($this->items, $callback));
}
return new static(array_filter($this->items));
}
When no callback is provided, array_filter
will be executed, also without a callback.
The PHP Manual states that:
If no callback is supplied, all empty entries of the array will be removed.
Values that are false
or null
are considered empty.
This means you can just call filter
without arguments:
$collection = collect([1, 2, null, 4, null, null, 7]);
$collection->filter();
// [1, 2, 4, 7]
All null
values will be removed from the collection.