What's the difference between Laravel's where
and whereLoose
methods?
The documentation says:
where()
:The where method uses strict comparisons when checking item values. Use the whereLoose method to filter using "loose" comparisons.
whereLoose()
:This method has the same signature as the where method; however, all values are compared using "loose" comparisons.
In this case, what does "loose comparisons" means?
The where
method uses strict comparison (===
), meaning it also checks the type of the value. If, for example, one is a string and the other a number, it won't ever match.
The whereLoose
method uses loose comparison (==
), meaning it won't check the type of the value. If, for example, one is a string and the other a number, it will still match if their values are the same.
$collection = collect([['price' => 100], ['price' => 200]]);
$collection->where('price', '100'); // []
$collection->whereLoose('price', '100'); // [['price' => 100]]
You can find a table of all the differences in the PHP docs.
Note: this is about to change in Laravel 5.3: the where
method will now use loose comparison, and the whereLoose
method will be removed. To use strict equality, you'll pass ===
as the 2nd argument:
$collection = collect([['price' => 100], ['price' => 200]]);
$collection->where('price', '100'); // [['price' => 100]]
$collection->where('price', '===', '100'); // []
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With