Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel collection filtering to avoid null records

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

like image 299
dev1234 Avatar asked Nov 27 '22 06:11

dev1234


2 Answers

You can use filter method to filter the users against your condition

$filteredUsers = $users->filter(function ($user, $key) {
    return $user->role != null;
});
like image 112
Haider Ali Avatar answered Dec 01 '22 00:12

Haider Ali


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.

like image 31
Tim Lewis Avatar answered Dec 01 '22 00:12

Tim Lewis