Home > Mobile >  I am looking for a way to set where (A or B) and C on laravel query builder
I am looking for a way to set where (A or B) and C on laravel query builder

Time:06-17

Is it possible to group search terms with Laravel's Eloquent query builder?

When I try this:

$criteria1 =  ['country ' => ['Malaysia','Korea']];
$criteria2 =  ['size' => 'big'];

Fruit::where($criteria1)->where($criteria2)->get();
   

it means (malaysia and korea) and big but I want (malaysia or korea) and big.

CodePudding user response:

You can just use whereIn:

Fruit::where("size", "big")
    ->whereIn("country", ["malaysia", "korea"])
    ->get();

Or group them together using a closure:

Fruit::where("size", "big")
    ->where(
        fn ($q) => $q->where("country", "malaysia")->orWhere("country", "korea")
    )
    ->get();

Actually, doing some testing I notice that passing an array with multiple values already creates a group with parentheses. So the absolute easiest answer, given your existing code, is to simply use orWhere() instead of where():

$criteria1 =  ['country' => 'malaysia' , 'country ' => 'korea'];
$criteria2 =  ['size' => 'big'];

Fruit::orWhere($criteria1)->where($criteria2)->get();

This results in:

SELECT * FROM fruits WHERE (country = 'malaysia' OR country = 'korea') AND size = 'big'

CodePudding user response:

Try this solution

Fruit::where($criteria2)->where(function ($q) use ($criteria1) {
    foreach ($criteria1 as $column => $value) {
        $q->orWhere($column, $value);
    }
})->get();
  • Related