Posts Learn Components new Snippets new Categories Tags About
/

Laravel Eloquent Query Using WHERE with OR AND OR?

Learn how to define the WHERE clause with OR AND OR condition in Laravel Eloquent and query your data the fluent way

Created on Oct 04, 2021

47 views

To perform a complex query that has OR AND OR in Laravel Eloquent, you can write your code by passing in a closure (anonymous function) to the WHERE function. Imagine the query condition below.
WHERE (a = 1 OR b = 2) AND (c = 3 OR d = 4);
To do that query in Laravel Eloquent you can write your or condition within the closure. This is important because you need to somehow scope it to each of the conditions. In this case, the closure will act like the "()" part. Do note that the MODELNAME is your actual modal name like "Post" or "User" modal.
<?php

MODELNAME::where(function($a) {
    $a->where('a', 1)->orWhere('b', 2);
})->where(function($a) {
    $a->where('c', 3)->orWhere('d', 4);
});

How to Display the RAW SQL


To display the raw SQL you can write the above code within the query log like below.
<?php

// Enable query log
\DB::enableQueryLog(); 

MODELNAME::where(function($a) {
    $a->where('a', 1)->orWhere('b', 2);
})->where(function($a) {
    $a->where('c', 3)->orWhere('d', 4);
});

// Show results of log
dd(DB::getQueryLog()); 

Other reads

new

If you like our tutorial, do make sure to support us with some coffee. We need the juice to write the content during the night 🤙🏻