Skeets
Skeets

Reputation: 4828

Is there a way to combine Laravel query builder conditions?

Say I have 2 query builders:

$builderA = User::where("happiness", ">", 5);
$builderB = User::where("color", "blue");

Other than typing out a new builder, is there a way I can combine these 2 builders, resulting in the builder shown below?

$combined = User::where("happiness", ">", 5)->where("color", "blue");

Upvotes: 3

Views: 2497

Answers (3)

Brian Lee
Brian Lee

Reputation: 18187

For more complex cases, you can use tap and mergeWheres:

$where = User::where('a', 1)->where('b', '>', 2)->where('c', '<', 2)->where('d', '<>', 2);

$combined = User::where('e', 5)->tap(function (Builder $builder) use ($where) {
    $builder->mergeWheres($where->wheres, $where->getBindings());
});

Laravel 5.6 added several methods for working with subqueries:

Upvotes: 6

DsRaj
DsRaj

Reputation: 2328

If you want to add the query on base of any conditions or matching with any input then you can try this:

$combinedUsers = User::query();
if(YourCondition){
    $combinedUsers = $combinedUsers->where("happiness", ">", 5);
}
if(YourCondition){
    $combinedUsers = $combinedUsers->where("color","blue");
}
if(YourCondition){
    $combinedUsers = $combinedUsers->orderBy("color");
}
$combinedUsers = $combinedUsers->get();

Upvotes: 0

Davit Zeynalyan
Davit Zeynalyan

Reputation: 8618

Yes you can.

$combinedUsers = User::where([
   ["happiness", ">", 5], 
   ["color" => "blue"]
])->get();

or

$combinedUsers = User::where([
   ["happiness", ">", 5], 
   ["color", "=", "blue"]
])->get();

In your case you must be use orWhere

// one request in db
$combinedUsers = User::where("happiness", ">", 5)->orWhere("color", "blue")->get();

// filter in Collection instance
$happyUsers = $combinedUsers->where("happiness", ">", 5); 
$blueUsers = $combinedUsers->where("color", "blue"); 

Alos you can use

$queryBulider = User::newQuery();
$queryBulider->...->get();

$queryBulider is instance of Illuminate\Database\Eloquent\Builder.

Upvotes: 2

Related Questions