S
S
stts2015-08-22 14:45:49
MySQL
stts, 2015-08-22 14:45:49

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);

Initially I tried something like this, but it didn't work.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
G
gsur, 2017-01-18
@gsur

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 question

Ask a Question

731 491 924 answers to any question