dev1234
dev1234

Reputation: 5706

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

Upvotes: 11

Views: 39122

Answers (7)

Davit Zeynalyan
Davit Zeynalyan

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

Priyanka
Priyanka

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

Zakaria Acharki
Zakaria Acharki

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

OtienoJulie
OtienoJulie

Reputation: 11

You can wrap everything within if($row->filter()->isNotEmpty()) this has worked for me in the past

Upvotes: 1

Tim Lewis
Tim Lewis

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

Azraar Azward
Azraar Azward

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

Haider Ali
Haider Ali

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

Related Questions