How do you wrap Laravel Eloquent ORM query scopes in parentheses when chaining

0 votes

In Eloquent, I'd like to generate this query:

SELECT * FROM table WHERE a=1 AND ( b=2 OR c=3 );

But I seem to be generating this query instead:

SELECT * FROM table WHERE a=1 AND b=2 OR c=3;

Here is my implementation and code:

$result = Model::aIsOne()->bIsTwoOrCIsThree()->get();

Model contains:

function scopeAIsOne($query) {
    return $query->where('a', 1);
}

function scopeBIsTwoOrCIsThree($query) {
    return $query->where('b', 2)->orWhere('c', 3);
}
Dec 2, 2020 in Laravel by kartik
• 37,530 points
360 views

1 answer to this question.

0 votes

Hello @kartik,

You can generate parentheses by passing a callback function to where().

Model::where('a',1)->where(function($query) {
    $query->where('b', 2)->orWhere('c',3);
})->get();

Hope it helps!!

Thank you!!

answered Dec 2, 2020 by Niroj
• 82,880 points

Related Questions In Laravel

0 votes
1 answer

What do you meant by dd() function in Laravel?

Hey @kartik dd stands for "Dump and Die." Laravel's ...READ MORE

answered Mar 20, 2020 in Laravel by Niroj
• 82,880 points
11,230 views
0 votes
1 answer

How can we create a record in Laravel using eloquent?

We need to create a new model ...READ MORE

answered Mar 20, 2020 in Laravel by Niroj
• 82,880 points
350 views
0 votes
1 answer

How to enable query log in Laravel?

Hello, You can use simple function that is ...READ MORE

answered Mar 23, 2020 in Laravel by Niroj
• 82,880 points
608 views
0 votes
1 answer

What do you mean by Rate Limiting?How can we access control in number of routes in an application ?

Hey kartik, Laravel includes a middleware to rate ...READ MORE

answered Mar 26, 2020 in Laravel by Niroj
• 82,880 points
204 views
+1 vote
1 answer

How to make anchor tag with routing using Laravel?

Hey @kartik, First you have to go to ...READ MORE

answered Mar 18, 2020 in Laravel by Niroj
• 82,880 points
10,629 views
0 votes
1 answer

What is redirection in Laravel?

Named route is used to give specific ...READ MORE

answered Mar 18, 2020 in Laravel by Niroj
• 82,880 points
1,182 views
0 votes
1 answer

How to install Laravel via composer?

Hello, This is simple you just need to ...READ MORE

answered Mar 23, 2020 in Laravel by Niroj
• 82,880 points
958 views
+1 vote
1 answer

What are named routes in Laravel and How can specify route names for controller actions?

Hey @kartik, Named routing is another amazing feature of ...READ MORE

answered Mar 23, 2020 in Laravel by Niroj
• 82,880 points
12,190 views
0 votes
1 answer

How to Make Laravel Eloquent “IN” Query?

Hello @kartik, Here is how you do in ...READ MORE

answered Aug 4, 2020 in Laravel by Niroj
• 82,880 points
212 views
0 votes
1 answer

How to alias a table in Laravel Eloquent queries using Query Builder?

Hello @kartik, You can use less code, writing ...READ MORE

answered Nov 11, 2020 in Laravel by Niroj
• 82,880 points
4,999 views