Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel where() vs whereLoose() methods

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?

like image 308
Jacson Avatar asked Nov 13 '15 16:11

Jacson


1 Answers

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'); // []
like image 116
Joseph Silber Avatar answered Oct 23 '22 06:10

Joseph Silber