DevonDahon
DevonDahon

Reputation: 8350

Exclude empty or null column with Laravel Eloquent

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

Answers (2)

Uzair Riaz
Uzair Riaz

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

pr1nc3
pr1nc3

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

Related Questions