Laravel eloquent where query examples

Laravel eloquent where query examples

In this article lets understand laravel eloquent where query examples. We will see where and, where or, where and-or-and, where or-and-or examples.

1 ) where – AND

Example 1:

$user = User::where('name','csp')->where('email','')->first();

select * from `users` where `name` = ‘csp’ AND email = ‘’;

A simple syntax where we apply direct where conditions t model. Multiple where simply apply where AND.

Example 2:

$user = User::where([

select * from users where name = 'csp' AND `email` = ‘’;

To apply multiple where with AND we can pass an array of conditions to model as above.

Laravel where and where

2 ) where – OR

Example :

$user = User::where('name','csp')->orWhere('email','')->first();

select * from `users` where `name` = ‘csp’ OR email = ‘’;

To apply where OR where use above syntax where we are defining where with orWhere on model.

Laravel orWhere

3 ) where – not

Example :

$users = User::whereNot('id', 1)->get();

select * from `users` where not `id` = 1

Its a simple where but will negate the expression.

laravel where not query

4) where AND-OR-AND

Example :

$users = User::where('type','customer')->where(function($query) {

select * from `users` where `type` = ‘customer’ AND (name = ‘csp’ OR email = ‘’);

In above syntax we are defining we want user with type as customer and name or email can be as above.

Laravel where and-or-and

5) where – OR-AND-OR

Example :

$users = User::where(function ($query) {
    $query->where('name', '=', 'csp')
          ->orWhere('name', '=', 'csp1');
})->where(function ($query) {
    $query->where('email', '=', '')
          ->orWhere('email', '=', '');

select * from `users` where (name = ‘csp’ OR name = ‘csp1’) AND (email = ‘’ OR email = ‘’);

The above one is bit complex and many times people gets confused how to use it. Is we simplify it, it’s just “WHERE (a = 1 OR b =1 ) AND (c = 1 OR d = 1)” in pseudo code. Where you can define all the different parameters as a, b, c, d or use it in repeat.

Laravel where or-and-or

That’s it on Laravel eloquent where query examples. Hope this find you helpful.

Read more articles on Laravel here.