Search

Laravel Collection Public API: whereIn

November 30, 2016 —John Koster

whereIn($key, array $values, $strict = true)

The whereIn method is used to filter the collection based on a given $key and an array of the possible $values that the $key can have. The method also defines an optional $strict parameter, which when an argument with a truth value of true is supplied, will cause the method to check the types of each item in the collection against the types in the supplied $values array ($strict is set to true by default). This method does not change the original Collection instance and will return a new, modified, Collection instance.

The following examples will use the following collection to demonstrate the whereIn method:

1<?php
2 
3// Create a new collection.
4$people = collect([
5 ['name' => 'Alice', 'age' => 26],
6 ['name' => 'Bob', 'age' => 34],
7 ['name' => 'Chris', 'age' => 26]
8]);

We can quickly get a subset of the $people collection based on their age. Assuming we wanted to retrieve all people whose age was 26 we could use the whereIn method like so:

1<?php
2 
3$results = $people->whereIn('age', [26]);

After the above code has executed, the $results variable will contain a value similar to the following output:

1Collection {
2 #items: array:2 [
3 0 => array:2 [
4 "name" => "Alice"
5 "age" => 26
6 ]
7 2 => array:2 [
8 "name" => "Chris"
9 "age" => 26
10 ]
11 ]
12}

To see the effects of the $strict argument, we can change the above example only slightly to cause the method to return no results:

1<?php
2 
3// Notice that the value in the array is
4// a string, not an integer.
5$results = $people->whereIn('age', ['26']);

Because the age of each person in the $people array is an integer and the item in the $values array in the previous code example is a string, the $results variable would be an empty Collection instance. To get this to work, simply pass false as the argument for the $strict parameter:

1<?php
2 
3// Disable type checking by supplying an
4// argument that evaluates to false
5// for the $strict parameter.
6$results = $people->whereIn('age', ['26'], false);

After the above code has executed, the $results variable would the same items as in our first example (both Alice and Chris would be returned).