1

I have this query:

$products = Product::whereIn('brand_id', $brand)->get();

which is returning result of selected brands. But if I want to add another fields such as min and max price it returns error, here is my code:

$brand = Input::has('brands') ? Input::get('brands') : [];
$min_price = Input::has('min_price') ? Input::get('min_price') : null;
$max_price = Input::has('max_price') ? Input::get('max_price') : null;

$products = Product::orWhere('price','>=',$min_price)
->orWhere('price','<=',$max_price)
->orWhereHas('brands',function($query){
  $query->whereIn('brand_id', $brand);
})->get();

error i get:

Illegal operator and value combination.

Sameer K
  • 799
  • 1
  • 7
  • 26
djhru
  • 336
  • 6
  • 28
  • As a note, you can shorten your `$min_price` and `$max_price` assignments. `Input::get` has a second parameter for a default value. By default, it will return `NULL`, but you can set it to something else, such as `$min_price = Input::get('min_price', 0); $max_price = Input::get('max_price', 100000000);` – aynber Mar 01 '18 at 15:10
  • @aynber i don't want to have default value. I want get values only if user provided. – djhru Mar 01 '18 at 15:18

1 Answers1

1

You need to check the input data and do not allow null in a query like this:

// $max_price is null
->orWhere('price', '>=', $max_price)

One of the input fields is null, that's why you're getting the error.

You also should add use() to the closure:

function($query) use($brand) {
    $query->whereIn('brand_id', $brand);
})
Alexey Mezenin
  • 158,981
  • 26
  • 290
  • 279
  • yes in this case my price field was empty. i want to be worked like if all used or only one of them used like that. – djhru Mar 01 '18 at 15:06
  • I've tried those ways like `isset($min_price) &&.....` but there was always one part broken, mostly returned products wouldn't be in price range i searched for. eg: i searched `100.000 - 500.000` i've got result from `50.000 - 1.500.000` – djhru Mar 01 '18 at 15:27