1

I have a small table and try to use some filters to get some specific data out of it.

My attempt:

$matchingCars = Car::where([
    ['brand', '=', request('brand')],
    ['model', '=', request('model')],
    ['price', '<', request('maxPrice')],
])->get();

Result:

Collection {#249 ▼
  #items: []
}

You can see nothing is returned. However, if I do the queries one by one and count the result, then I get a number higher than 0, so there are models who pass my filters!

    $checkBrands = Car::where('brand', '=', request('brand'))->get(); 
    $checkModels = Car::where('model', '=', request('model'))->get(); 
    $checkPrice  = Car::where('price', '<', request('maxPrice'))->get(); 

    echo count($checkBrands) . "<br>";   //output: 1
    echo count($checkModels). "<br>";    //output: 1
    echo count($checkPrice). "<br>";     //output: 8
    die;

Why are they not stored in the collection?

3
  • 1
    Just because each individual one has results doesn't mean their intersection does. Use orWhere to be sure that's the problem. If you get 10 results that means the intersection is empty. Commented Feb 25, 2017 at 18:20
  • Oh, thats true, thanks for the hint! Commented Feb 25, 2017 at 18:26
  • Yes the problem was indeed because the car with correct Brand and correct Model was much more expensive then my max price, so thats why the collection was empty.. Commented Feb 25, 2017 at 18:48

3 Answers 3

4

You need to orWhere():-

$matchingCars = Car::where('brand', '=', request('brand'))
                   ->orwhere('model', '=', request('model'))
                   ->orwhere('price', '<', request('maxPrice'))->get()

Note:-

you said:- However, if I do the queries one by one and count the result, then I get a number higher than 0

But this doesn't mean that combination of all these three queries with AND will return result.

So apply OR condition like above.

Sign up to request clarification or add additional context in comments.

Comments

1

Try this:

$matchingCars = Car::where('brand', '=', request('brand'))
    ->where('model', '=', request('model'))
    ->where('price', '<', request('maxPrice'))->get();

Comments

1
$matchingCars = Car::where('brand', '=', request('brand'))
                   ->where('model', '=', request('model'))
                   ->where('price', '<', request('maxPrice'))->get();

And make sure that that you have the right things returned by request()

2 Comments

Where is the difference between your answer and the answer of @Paras?
I believe not, but you can see it as a confirmation of his answer. He was just faster. :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.