'Avoid "where" clause grouping when applying multiple where clauses inside the same scope

I have this scope in my Model:

function extraFiltersScope($query){
    $query->where('first_name', 'test')->orWhere('name', 'testing');
    return $query;
}

I'm applying the clause like this:

$query = User::where('age', 30')->extraFilters()->toSql();

Expected SQL would be:

select * from users where age=30 and first_name='test' or name='testing'

I'm getting this:

select * from users where age=30 and (first_name='test' or name='testing')

It seems that that's the normal behavior since both "where" clauses are being applied inside the same scope. Is there a workaround to tell the builder to now group them?

Of course, my logic is much more complex than this, otherwise I could simply have a scope method for each one. I need to apply several filters on the same scope but without nesting.

Thanks.



Solution 1:[1]

Try using DB::raw

    $query->where(DB::raw("( age = 30 and first_name = 'test')"))
           ->where("name", "=", testing)
    return $query;

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1