[php] Laravel 4 Eloquent Query Using WHERE with OR AND OR?

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?

This question is related to php laravel eloquent laravel-query-builder

The answer is


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


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);
    }
});

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();

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();

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');

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);
});

$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);
        })

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;    
}

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);
    });
});

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);
});

Examples related to php

I am receiving warning in Facebook Application using PHP SDK Pass PDO prepared statement to variables Parse error: syntax error, unexpected [ Preg_match backtrack error Removing "http://" from a string How do I hide the PHP explode delimiter from submitted form results? Problems with installation of Google App Engine SDK for php in OS X Laravel 4 with Sentry 2 add user to a group on Registration php & mysql query not echoing in html with tags? How do I show a message in the foreach loop?

Examples related to laravel

Parameter binding on left joins with array in Laravel Query Builder Laravel 4 with Sentry 2 add user to a group on Registration Target class controller does not exist - Laravel 8 Visual Studio Code PHP Intelephense Keep Showing Not Necessary Error The POST method is not supported for this route. Supported methods: GET, HEAD. Laravel How to fix 'Unchecked runtime.lastError: The message port closed before a response was received' chrome issue? Post request in Laravel - Error - 419 Sorry, your session/ 419 your page has expired Expected response code 250 but got code "530", with message "530 5.7.1 Authentication required How can I run specific migration in laravel Laravel 5 show ErrorException file_put_contents failed to open stream: No such file or directory

Examples related to eloquent

Eloquent: find() and where() usage laravel How to select specific columns in laravel eloquent Laravel Eloquent where field is X or null Laravel Eloquent limit and offset laravel collection to array Eloquent get only one column as an array Laravel 5.2 - Use a String as a Custom Primary Key for Eloquent Table becomes 0 Laravel 5.2 - pluck() method returns array Eloquent ORM laravel 5 Get Array of ids eloquent laravel: How to get a row count from a ->get()

Examples related to laravel-query-builder

Get Specific Columns Using “With()” Function in Laravel Eloquent How to Create Multiple Where Clause Query Using Laravel Eloquent? Creating and Update Laravel Eloquent How Do I Get the Query Builder to Output Its Raw SQL Query as a String? How to Use Order By for Multiple Columns in Laravel 4? Laravel 4 Eloquent Query Using WHERE with OR AND OR? A JOIN With Additional Conditions Using Query Builder or Eloquent Get the Query Executed in Laravel 3/4