Laravel where & orWhere eloquent Query Examples

Laravel where() and orWhere() eloquent Query Example; In this tutorial you will learn how to use where and or where condition eloquent query in laravel application. The orwhere query needs when we need to add check one or another column and get the records.

While building your Laravel query whether using Eloquent Query or DB Query builder, you often have to use multiple where conditions. This tutorial will take several examples of laravel orWhere conditions with query builder and eloquent model.

Example 1:

Here is the basic example to use where and orWhere in laravel app using DB table;

Laravel Query:

public function index()
{
    $users = DB::table('users')
                    ->where('id', 2)
                    ->orWhere('email', 'test@gmail.com')
                    ->get();
  
    dd($users);                    
}

Sql Query: This query printed the sql query like as below:

SELECT *
  FROM users
  WHERE id = '2' OR email = 'test@gmail.com'

Example 2:

Here the example show you how to use $query builder with laravel where and orWhere easy way. If you need to add multiple where and orwhere query then you can use something like below;

Laravel Query:

$a='foo', $b='bar', $c='john', $d='doe';


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

Sql Query: This example sql result show something like this:

SELECT * FROM <table> WHERE (a='foo' or b='bar') AND (c='john' or d='doe');

Example 3:

In this example we use to ge dyanamic data for where and orWhere with whereNull and whereNotNull query builder.

$authUser = Auth::user();
$tenantId = '5asf45asf5454asdf54';

$tasks = Task::where('user_id', $authUser->id)
             ->where(function($query) use ($tenantId) {
                   $query->where(function($q) use ($tenantId) {
                       $q->whereNull('tenant_id');
                   })
                   ->orWhere(function($q1) use ($tenantId) {
                       $q1->whereNotNull('tenant_id')
                           ->where('tenant_id', $tenantId);
                   });
               })
             ->get();

dd($tasks);             

I hope you enjoy with Laravel Where and orWhere Condition using Eloquent Query steps.

Leave a Comment