Laravel Eloquent Query: Using WHERE with OR AND OR?
Asked Answered
D

16

417

How do I say WHERE (a = 1 OR b =1 ) AND (c = 1 OR d = 1)

For more complicated queries am I supposed to use raw SQL?

Duisburg answered 8/6, 2013 at 1:29 Comment(0)
E
696

Make use of Logical Grouping (Laravel 7.x/4.2). For your example, it'd be something like this:

Model::where(function ($query) {
    $query->where('a', '=', 1)
          ->orWhere('b', '=', 1);
})->where(function ($query) {
    $query->where('c', '=', 1)
          ->orWhere('d', '=', 1);
});
Erection answered 8/6, 2013 at 1:38 Comment(3)
Just do function ($query) use ($param1, $param2)...; Oh, you deleted your comment.Erection
Correct link to Laravel doco is: laravel.com/docs/queries#advanced-where-clausesIngrown
laravel.com/docs/8.x/queries#logical-groupingInflated
F
134

If you want to use parameters for a,b,c,d in Laravel 4

Model::where(function ($query) use ($a,$b) {
    $query->where('a', '=', $a)
          ->orWhere('b', '=', $b);
})
->where(function ($query) use ($c,$d) {
    $query->where('c', '=', $c)
          ->orWhere('d', '=', $d);
});
Fountainhead answered 4/3, 2014 at 13:31 Comment(2)
works for version 4 to latest version 8.17Watermark
Worked for me when I wanted to implement filter in a query that had orWhere. Thank you!Murdocca
Q
35

Incase you're looping the OR conditions, you don't need the the second $query->where from the other posts (actually I don't think you need in general, you can just use orWhere in the nested where if easier)

$attributes = ['first'=>'a','second'=>'b'];

$query->where(function ($query) use ($attributes) 
{
    foreach ($attributes as $key=>value)
    {
        //you can use orWhere the first time, doesn't need to be ->where
        $query->orWhere($key,$value);
    }
});
Queasy answered 1/4, 2015 at 14:7 Comment(1)
I think you will have to add the use keyword to use the attributes variable inside the where.Saltwater
E
34

if you want to use parentheses in laravel 4 and don't forget return
In Laravel 4 (at least) you need to use $a, $b in parentheses as in the example

$a = 1;
$b = 1;
$c = 1;
$d = 1;
Model::where(function ($query) use ($a, $b) {
    return $query->where('a', '=', $a)
          ->orWhere('b', '=', $b);
})->where(function ($query) use ($c, $d) {
    return $query->where('c', '=', $c)
          ->orWhere('d', '=', $d);
});

This is my result: enter image description here

Erasion answered 13/9, 2015 at 6:29 Comment(0)
B
15

Simply Use in Laravel Eloquent:

$a='foo', $b='bar', $c='john', $d='doe';

Coder::where(function ($query) use ($a, $b) {
    $query->where('a', '=', $a)
          ->orWhere('b', '=', $b);
})->where(function ($query) use ($c, $d) {
    $query->where('c', '=', $c)
          ->orWhere('d', '=', $d);
})->get();

Will produce a query like:

SELECT * FROM <table> WHERE (a='foo' or b='bar') AND (c='john' or d='doe');
Boudreaux answered 23/12, 2017 at 19:40 Comment(0)
L
10

Another way without using Modal

Database: stocks Columns:id,name,company_name,exchange_name,status enter image description here

  $name ='aa'
  $stocks = DB::table('stocks')
            ->select('name', 'company_name', 'exchange_name')
            ->where(function($query) use ($name) {
                $query->where('name', 'like', '%' . $name . '%')
                ->orWhere('company_name', 'like', '%' . $name . '%');
            })
            ->Where('status', '=', 1)
            ->limit(20)
            ->get();
Latinity answered 21/9, 2018 at 18:39 Comment(0)
H
9

You can also query the first or condition and later you can apply another or condition

$model = Model::where('a',1)->orWhere('b',1);

now apply another condition on that $model variable

$model1 = $model->where('c',1)->orWhere('d',1)->get();
Haphazardly answered 22/4, 2015 at 10:31 Comment(0)
F
8

$a, $b, $c, $d can be dynamic values by the query

 ->where(function($query) use ($a, $b)
        {
            $query->where('a', $a)
                  ->orWhere('b',$b);
        })
 ->where(function($query) use ($c, $d)
        {
            $query->where('c', $c)
                  ->orWhere('d',$d);
        })
Flabbergast answered 7/8, 2016 at 6:50 Comment(0)
N
6

You can use:

Model::where('table_column', 'value')->orWhere('table_column', 'value')->get()
Nervine answered 20/1, 2022 at 10:54 Comment(0)
T
5

You can also use query scopes to make things a bit tidier, so you can do something like:

Invoice::where('account', 27)->notPaidAt($date)->get();

Then in your model

public function scopeNotPaidAt($query, $asAt)
{
    $query = $query->where(function ($query) use ($asAt) { 
        $query->where('paid', '=', '0000-00-00')->orWhere('paid', '>=', $asAt); 
    });
    return $query;    
}
Twine answered 16/4, 2015 at 14:50 Comment(0)
P
5
YourModel::where(function ($query) use($a,$b) {
    $query->where('a','=',$a)
          ->orWhere('b','=', $b);
})->where(function ($query) use ($c,$d) {
    $query->where('c','=',$c)
          ->orWhere('d','=',$d);
});
Pend answered 7/8, 2018 at 13:26 Comment(0)
P
4
ModelName::where(function ($query) use ($a) {
    $query->where('a', '=', $a)->orWhereNull('a');

})
->where(function ($query) use ($b,$c) {
    $query->where('b', '=', $b)
          ->orWhere('c', '=', $c);
})->where('d',$d);

OUTPUT QUERY:

SELECT * FROM ModelName WHERE (a='a' or a is null) AND (b='b' or c='c') AND d='d';

Psychophysiology answered 6/10, 2022 at 14:3 Comment(0)
C
2

Best way to use sql brackets use callback function in laravel eloquent.

YourModal::where(function ($q) {
    $q->where('a', 1)->orWhere('b', 1);
})->where(function ($q) {
    $q->where('c', 1)->orWhere('d', 1);
});

You don't have to use = symbol, it's come as the default

Lest say if you have a query that contain brackets inside a brackets

WHERE (a = 1 OR (b = 1 and c = 5))


YourModal::where(function ($q) {
    $q->where('a', 1)->orWhere(function($q2){
      $q2->where('b', 1)->where('c', 5);
    });
});

lest say you want to make values dynamics

YourModal::where(function ($q) use($val1, $val2) {
    $q->where('a', $val1)->orWhere(function($q2) use($val2){
      $q2->where('b', $val2)->where('c', $val2);
    });
});
Cargo answered 17/6, 2019 at 11:46 Comment(0)
C
1

For eloquent query builder the following query will not work:

MODELNAME::where('a', 1)->orWhere('b', 1)->where('c', 1)->orWhere('d', 1);

But you can use this code:

MODELNAME::where(function($a) {
    $a->where('a', 1)->orWhere('b', 1);
})->where(function($a) {
    $a->where('c', 1)->orWhere('d', 1);
});

You can use the second query and it will work perfectly.

Cloy answered 10/3, 2021 at 5:24 Comment(0)
N
1

This works for me

$business = Model::where('model_id', $model_id1)->orWhere('model_id', $model_id2)->first();
Necolenecro answered 1/11, 2021 at 23:23 Comment(0)
N
1

If you are using PHP 7.4+ you can also use arrow functions. They automatically capture variables from the surrounding scope, so you don't need to use the use() keyword.

Model::query()
  ->where(fn($query) => $query->where("a", "=", $a)->orWhere("b", "=", $b))
  ->where(fn($query) => $query->where("c", "=", $c)->orWhere("d", "=", $d));
Nymphalid answered 18/3 at 12:29 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.