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
You can use filter
method to filter the users against your condition
$filteredUsers = $users->filter(function ($user, $key) {
return $user->role != null;
});
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With