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

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

Laravel 5

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

public function whereIn(
    $key,
    $values,
    $strict = false
);

Example Use

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

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

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:

$results = $people->whereIn('age', [26]);

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

Collection {
  #items: array [
    0 => array [
      "name" => "Alice"
      "age"  => 26
    ]
    2 => array [
      "name" => "Chris"
      "age"  => 26
    ]
  ]
}

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

// Notice that the value in the array is
// a string, not an integer.
$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:

// Disable type checking by supplying an
// argument that evaluates to false
// for the $strict parameter.
$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).

Start the Discussion

Leave a comment

Subscribe to our newsletter