Leon
Leon

Reputation: 1292

Filter an object in Laravel 4.1

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?

Upvotes: 0

Views: 1766

Answers (2)

Grzegorz Gajda
Grzegorz Gajda

Reputation: 2474

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();

Upvotes: 1

patricus
patricus

Reputation: 62238

Since you're doing a direct "equals" comparison, Laravel's Collection has a where() method you can use. For example:

$users = $media->campaign->users;
$users->where('suspended', 0);

This is a good option if you already have the Collection. If, however, you have control over generating the Collection, it would be more beneficial to only get the actual data you're looking for. In this case, you can add the where clause to the SQL statement, so you will only retrieve the final records you want. For example:

$users = $media->campaign->users()->where('suspended', '=', 0);

NB: the where() method on the Collection and the where() method on the query builder have different signatures. The query builder lets you pass in an operator to use ('=', '>', '<', etc). The Collection only does a direct equals comparison. This trips up a lot of people.

Upvotes: 0

Related Questions