Pixel
Pixel

Reputation: 910

Eloquent Laravel Where And Or And

I would like to make Sql request like this :

Get the ((Age > 10 AND Weight > 50) OR Name = Jack) AND Actif = 1

My Eloquent request look like this :

$user = DB::table('users')
    ->where('Age', '>=', 10)
    ->where('Weight', '>=', 50)
    ->orWhere('Name', 'Jack')
    ->where('Actif', 1)
    ->get();

But actually it will return the result Jack although this column Actif is set to 0.

Upvotes: 3

Views: 1050

Answers (1)

num8er
num8er

Reputation: 19372

If we look at nesting of where part so it will be like this:

$sites = DB::table('users')
    ->where(function($q) {                       // (
      $q->where(function($q){                    //   (
             $q->where('Age', '>=', 10)          //     Age > 10
               ->where('Weight', '>=', 50);      //     AND Weight > 50
        })                                       //   )
        ->orWhere('Name', 'Jack');               //   OR Name = Jack
    })                                           // )
    ->where('Actif', 1)                          // AND Actif = 1
    ->get();

Upvotes: 5

Related Questions