3

Take a look at the following query:

    $testQuery = Customer::where('company_id', auth()->user()->company_id);

    $testQuery
        ->where('name', 'like', '%test%')
        ->orWhere('age', '>', 22);

    dd($testQuery->toSql());

this produces the following SQL query:

select * from customers where (company_id = ? and name like ? or age > ?) and customers.deleted_at is null

What I am after is something like this:

select * from customers where company_id = ? and (name like ? or age > ?) and customers.deleted_at is null

How can I achieve this? i.e. the first where condition of company_id = ? more important than there rest of the filters on name and age?

Right now, based on how the query builder is constructing the query, I am seeing results from other company_id than the one I've specified in my query.

2
  • What version of Laravel are you using? Commented Sep 21, 2019 at 23:56
  • I am using laravel 6. Commented Sep 21, 2019 at 23:57

1 Answer 1

4

I believe you want to use parameter grouping.

By using closures, you can tell the query builder what should be enclosed in parenthesis:

$testQuery = Customer::where('company_id', auth()->user()->company_id)
                     ->where(
                         function ($query) {
                           $query->where('name', 'like', '%test%')
                                 ->orWhere('age', '>', 22);
                      })->get();
Sign up to request clarification or add additional context in comments.

Comments

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.