This is a very interesting question.
0 = 1 will always be false, so your query will return zero rows. But why is that?
Because by setting
->whereIn('size', $size)
Laravel assumes that you always want the returned rows to be one of the sizes in the passed array. If you don't pass any values ββin the array, Laravel can't do it where size IN () , because it will be a syntax error (you basically say give me all the rows matching that size, but you won't miss the size). Therefore, if the array is empty, it simply puts 0 = 1 .
To tell Laravel if the size is not passed, so as not to add a condition for the size, just put a simple check in front of it.
$product = new Product; if (!empty($sizes)) { $product = $product->whereIn('size', $sizes); } $products = $product->get();
Btw this behavior is a fix . In previous versions of Laravel, if you passed an empty array, you just had an exception for a syntax error. Now it is only processed by setting 1 = 0
source share