Home / Snippets / Laravel Eloquent Query Using WHERE with OR AND OR?
Laravel Eloquent Query Using WHERE with OR AND OR? cover

Laravel Eloquent Query Using WHERE with OR AND OR?

2.1K

3 years ago

0 comments

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

notion avatar

Alaz

Week-end developer currently experimenting with web, mobile, and all things programming.

Topics:

Frontend

Resource

Average

Average

Support Us

If you like our tutorial, support us by being our Patreon or buy us some coffee ☕️

Welcome to PostSrc V3

PostSrc Dark Logo

You have to login to favorite this