Reputation: 8350
How to exclude empty or null columns when getting collections with Laravel Eloquent ?
I tried this but unsuccessfully:
User::where('last_name', 'foo')->get()->filter()
Upvotes: 1
Views: 2018
Reputation: 919
In addition to @pr1nc3 answer, there is a method ->reject()
for this specific purpose. It rejects/excludes the items that match the condition. For your case, use it like this:
User::where('last_name', 'foo')->get()->reject(function ($value) { return empty($value); });
All the values that meet the condition empty($value)
i.e. the values that are null/empty will be rejected.
Upvotes: 2
Reputation: 8338
You can do the filter in 2 steps
$users = User::where('last_name', 'foo')->get(); //returns your collection
Then you can use filter for your collection like:
$myFilteredCollection = $users->filter(function ($value) { return !empty($value); });
If you still need it in one line then you can do:
Of course you can merge it into one, get()
actually outputs the collections but looks a bit ugly i think. Keep your actions separate.
$users = User::where('last_name', 'foo')->get()->filter(function ($value) { return !empty($value); });
Upvotes: 1