1

How to produce query like below in laravel eloquent

SELECT *
FROM TABLE
WHERE column1=value1 
and (
        (column2=value2 or column3=value3) 
     or (column4=value4 or column5=value5)
)

Please help.

2
  • What have you tried so far? Did you look at the documentation? Commented Jun 2, 2018 at 12:14
  • Can you please give feedback on the answers? Commented Jun 18, 2018 at 23:05

3 Answers 3

2

Your query can be expressed as

SELECT * 
FROM table 
WHERE column1=value1 
AND (
       column2=value2 
    or column3=value3 
    or column4=value4 
    or column5=value5
)

To use above in laravel you can follow Parameter Grouping guide from docs

DB::table('table')
    ->where('column1', $value1)
    ->where(function ($query) use ($value2, $value3, $value4, $value5) {
        $query->where('column2', $value2)
          ->orWhere('column3', $value3)
          ->orWhere('column4', $value4)
          ->orWhere('column5', $value5)
          ;
    })
    ->get();
Sign up to request clarification or add additional context in comments.

Comments

0

You need to use two nested where() statements:

DB::table('the_table')
    ->where('column', 'val')
    ->where(function ($q) {
        $q->where('column1', 'val1')
            ->orWhere('column2', 'val2');
    })
    ->where(function ($q) {
        $q->where('column3', 'val3')
            ->orWhere('column4', 'val4');
    })
    ->get()

If you need to pass a variable to the nested where(), you need to add a use on the inline function:

DB::table('the_table')
    ->where('column', $val)
    ->where(function ($q) use ($val1, $val2) {
        $q->where('column1', $val1)
            ->orWhere('column2', $val2);
    })
    ->where(function ($q) {
        $q->where('column3', 'val3')
            ->orWhere('column4', 'val4');
    })
    ->get()

Comments

0

Try it

DB::table('the_table')
    ->where('column1', 'value1')
    ->where(function ($query) {
        $query->where(function ($query) {
            $query->where('column2', 'value2')
                ->orWhere('column3', 'value3');
        })->orWhere(function ($query) {
            $query->where('column4', 'value4')
            ->orWhere('column5', 'value5');
        });
    })->get();

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.