Laravel Collections where()


Example

You can select certain items out of a collection by using the where() method.

$data = [
    ['name' => 'Taylor',  'coffee_drinker' => true],
    ['name' => 'Matt', 'coffee_drinker' => true]
];

$matt = collect($data)->where('name', 'Matt');

This bit of code will select all items from the collection where the name is 'Matt'. In this case, only the second item is returned.

Nesting

Just like most array methods in Laravel, where() supports searching for nested elements as well. Let's extend the example above by adding a second array:

$data = [
    ['name' => 'Taylor',  'coffee_drinker' => ['at_work' => true, 'at_home' => true]],
    ['name' => 'Matt', 'coffee_drinker' => ['at_work' => true, 'at_home' => false]]
];

$coffeeDrinkerAtHome = collect($data)->where('coffee_drinker.at_home', true);

This will only return Taylor, as he drinks coffee at home. As you can see, nesting is supported using the dot-notation.

Additions

When creating a Collection of objects instead of arrays, those can be filtered using where() as well. The Collection will then try to receive all desired properties.

5.3

Please note, that since Laravel 5.3 the where() method will try to loosely compare the values by default. That means when searching for (int)1, all entries containing '1' will be returned as well. If you don't like that behaviour, you may use the whereStrict() method.