Laravel - Query Builder - Or Where Clauses
When chaining together calls to the query builder's where
method, the "where" clauses will be joined together using the and
operator. However, you may use the orWhere
method to join a clause to the query using the or
operator. The orWhere
method accepts the same arguments as the where
method:
$users = DB::table('users')
->where('votes', '>', 100)
->orWhere('name', 'John')
->get();
If you need to group an "or" condition within parentheses, you may pass a closure as the first argument to the orWhere
method:
$users = DB::table('users')
->where('votes', '>', 100)
->orWhere(function($query) {
$query->where('name', 'Abigail')
->where('votes', '>', 50);
})
->get();
The example above will produce the following SQL:
select * from users where votes > 100 or (name = 'Abigail' and votes > 50)
You should always group orWhere
calls in order to avoid unexpected behavior when global scopes are applied.