Search

Laravel Collection Public API: whereLoose

November 30, 2016 —John Koster

whereLoose($key, $value)

The whereLoose method operates similar to the where method. It filters the collection item's by checking that the given $key has some value equal to the provided $value. The whereLoose method does not check to make sure the item's value and the provided $value have the same data type. This is the fundamental difference between the where (discussed in the Laravel Collection Public API: where article) and whereLoose methods. The whereLoose method returns an instance of Collection and does not modify the original collection in any way.

The following code example demonstrates the usage of the whereLoose method:

1<?php
2 
3use Illuminate\Support\Collection;
4 
5// Create a new collection.
6$collection = new Collection([
7 [
8 'genus' => 'Canis',
9 'name' => 'tundra wolf',
10 'age' => '2'
11 ],
12 [
13 'genus' => 'Canis',
14 'name' => 'arctic wolf',
15 'age' => 4
16 ],
17 [
18 'genus' => 'Cucumis',
19 'name' => 'cucumber',
20 'age' => 2
21 ]
22]);
23 
24$results = $collection->whereLoose('age', 2);

After the above code has executed, the $results variable would an instance of Collection and contain a value similar to the following output:

1object(Illuminate\Support\Collection)[136]
2 protected 'items' =>
3 array (size=2)
4 0 =>
5 array (size=3)
6 'genus' => string 'Canis' (length=5)
7 'name' => string 'tundra wolf' (length=11)
8 'age' => string '2' (length=1)
9 2 =>
10 array (size=3)
11 'genus' => string 'Cucumis' (length=7)
12 'name' => string 'cucumber' (length=8)
13 'age' => int 2

It can be observed that the two age values have different data types, but were still returned in the $results collection.

The whereLoose method is a shortcut to calling the where method with optional parameters. In fact, the following two examples would produce the same results and are functionally equivalent:

1<?php
2 
3$results = $collection->whereLoose('age', 2);
4 
5$results = $collection->where('age', 2, false);

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.