Answer the question
In order to leave comments, you need to log in
How to add whereHas by condition in Laravel 5?
The essence of the question is quite simple and should not have arisen on other frameworks.
I need to use ELOQUENT ORM to build a compound query depending on the passed parameters (added or not an additional parameter whereHas(...)) Tell me
how this is implemented
$req=Object::whereHas('address',function($q){
$q->where('city_id','=',Request::input('city_id'));
});
if(!empty($input['category_id'])){
$cat=Cat::where('id','=',$input['category_id'])->first();
if($cat->isLeaf()){
$req=Object::whereHas('address',function($q){
$q->where('city_id','=',Request::input('city_id'));
});
$req->whereHas('category',function($q){
$q->where('id','=',Request::input('category_id'));
});
$req->get();
$objects=$req->get();
print_r($objects);
}
}
$objects=$req->get();
print_r($objects);
Answer the question
In order to leave comments, you need to log in
I don’t know if it’s relevant, but after fiddling with a similar problem for a while, I found this solution:
- Take the initial instance of the request
- We conditionally return the results of the query with different where, and of course the initial where is involved (although it is not required)
if (a > b)
return $query->where('name', 'John')->get();
elseif (b > a)
return $query->where('lastname', 'Winners')->get();
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question