Search code examples
laraveleloquentwhere-in

Using whereIn and where in Laravel eloquent query builder


I have been trying to do a query with laravel eloquent query builder but without success.

This is what I want to achieve: I have a webshop with laptops. People can search by brand, screen diameter and processor. My table is called 'laptops' with columns 'specsTag', 'screen_diameter' and 'processor'. I'm using checkboxes. So the request is an array and may look like

['HP','Apple', '12 inch', 'Intel Core M']

First I want to get all brands in the array as a collection and filter them accordingly using the values in the array.

I tried several things. I.e. trying to search on screen diameter.

Suggestions are very appreciated.


Solution

  • You can try this

    $laptops = Laptop::whereIn('specsTag',$requestArray)->where(function($query) use ($requestArray){
                    foreach($requestArray as $item){
                        $query->orWhere('screen_diameter','=',$item);
                    }
                })->get();
    

    Assuming you have $requestArray like this

    $requestArray = ['HP','Apple' '12 inch', 'Intel Core M'];
    

    You will get sql like this

    select * from `laptops` where `specsTag` in (?, ?, ?, ?) and (`screen_diameter` = ? or `screen_diameter` = ? or `screen_diameter` = ? or `screen_diameter` = ?)