Ad

Filter An Object In Laravel 4.1

- 1 answer

I am very new to Laravel and php and i am facing an issue with a collection. The collection is generated in this way:

$users = $media->campaign->users;

Which return this data:

[{id: 1, name: "name", suspended: 0},{id: 2, name: "name2", suspended: 1}]

How can i filter this object in laravel 4.1 to get only the elements that have 0 as suspended?

Ad

Answer

Use array_filter(array $array[, callable $callback[, int $flag]]):

array_filter($users, function($value) {
    return($value->suspended === 0);
});

Check more in Laravel 4.2 documentation, Taylor wrote there that filtering collections use array_filter function. Also you should can use $users = $users->filter(function($user) {}); method.

Also, thanks to @xAoc, you can use filtering on SQL query:

$users = $media->campaign
    ->users()
    ->where("suspended", "=", 0)
    ->get();
Ad
source: stackoverflow.com
Ad