Showing posts with label where. Show all posts
Showing posts with label where. Show all posts

Saturday, February 11, 2017

Laravel adnance query builder using and or conditions

It is very important to make query dynamically based on what parameters we received. Best way to do this using Laravel is use query as a function. Background color yellow show how it works.


DB::table('users')
        ->where('name', '=', 'John')
        ->where(function($query) use($params) {
            $query->where('votes', '>', 100);
            $query->orWhere('title', '<>', 'Admin');
        })->get();

The query above will produce the following SQL:

select * from users where name = 'John' 
and (votes > 100 or title <> 'Admin') 

Or you can do below:

$where = [
    ['name', '=', "Some name"],
    ["OR" => function($q) {
        $q->where("type", "=", "EMPLOYEE");
        $q->orWhere("type", "=", "SUPERVISOR");
    }]
];


$list = DB::table('employees')->where($where)->get();