Reputation: 5706
is there an inbuilt way to loop through collections and return only the objects that are meeting a specific condition?
like skip all records that has $user->role === null
Upvotes: 11
Views: 39122
Reputation: 8618
This is what you wont. See docs https://laravel.com/docs/5.5/collections#method-where
$result = $collection->where('role', null);
Upvotes: 4
Reputation: 311
For laravel collection, whereStrict
is perfect for filtering to avoid null records.
Because whereStrict compares value + datatype.
$result = $collection->whereStrict('role', null);
Upvotes: 2
Reputation: 67505
You could use the whereNotNull()
method that verifies if the value of the given column is NULL :
User::whereNotNull('role')->get();
Upvotes: 2
Reputation: 11
You can wrap everything within if($row->filter()->isNotEmpty())
this has worked for me in the past
Upvotes: 1
Reputation: 29258
You actually don't even need the ->filter
method if you're using Eloquent
. If role
is a relationship of your User
model, you can simply call:
$users = User::has("role")->get();
This will automatically return only Users that have a role
, or where $user->role
is not null.
Upvotes: 9
Reputation: 1624
you could use reject, filter
functions to achieve this
$users = User::all();
$users->each(function($users) {
$users->roles->reject(function($role) {
return $role->rule === null;
});
});
Please refer to this to use filter -> http://laravel.com/docs/5.6/collections#method-filter
Upvotes: 3
Reputation: 1121
You can use filter
method to filter the users against your condition
$filteredUsers = $users->filter(function ($user, $key) {
return $user->role != null;
});
Upvotes: 19