Search

Laravel 5 Collections: Filtering a Collection Based On Key Presence With whereIn

April 22, 2018 —John Koster

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.

#Signature

1public function whereIn(
2 $key,
3 $values,
4 $strict = false
5);

#Example Use

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

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

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$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 [
3 0 => array [
4 "name" => "Alice"
5 "age" => 26
6 ]
7 2 => array [
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// Notice that the value in the array is
2// a string, not an integer.
3$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// Disable type checking by supplying an
2// argument that evaluates to false
3// for the $strict parameter.
4$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).

Some absolutely amazing
people

The following amazing people help support this site and my open source projects ♥️
If you're interesting in supporting my work and want to show up on this list, check out my GitHub Sponsors Profile.