Search code examples
laravellaravel-5.4eager-loadingeloquent

How to do laravel eager loading with multiple constraints?


$institutes = Institute::with(['address' => function($query){
                 $query->whereCityId(Input::get('city_id'));
                 $query->whereIn('area_id',Input::get('area_id'));
              }])->get();

Invalid argument supplied for foreach()


Solution

  • It does work but it returns

    address: null
    

    wherever the condition matches. But it returns all institutes. Either we can use filter on the collection or whereHas

    $institutes = Institute::whereHas('address', function ($query) use ($city_id) {
                       $query->whereCityId($city_id);
                  })->get();
    

    or

    $institutes = Institute::with(['address' => function ($query) use ($city_id) {
                       $query->whereCityId($city_id);
                  }])->get()->filter(function ($institute){ 
                       return $institute->address != null; 
                  });