Ad

Query Builder Filter For Multi Level Deep Relationship In Laravel

I have a selection of plots which each belong to a development by a hasManyThrough relationship through housetypes. I want to filter these by development on their overview page. Plots has a housetype_id column and housetypes has a development_id column.

public function plots()
  {
    return $this->hasManyThrough(Plot::class, Housetype::class);
  }

When I use my filter it returns the developments ID number as $development, I then need this to only show plots which are linked to that development.

I have looked into using whereHas or Join methods but have been unable to figure this out. Current filter scope is below. Thanks

public function scopeFilterDevelopment($query)
    {
      $development = request()->input('filter_development');

      if ($development == "") {
        return;
      }

      if(!empty($development)){
        $query->where('development_id', $development);
      }
    }
Ad

Answer

It was a whereHas that solved this in the end! (another developer at work walked me through this)

Relationship -

public function housetype()
    {
      return $this->belongsTo(Housetype::class);
    }

Function -

public function scopeFilterDevelopment($query)
    {
      if (request()->input('filter_development') == "") {
        return;
      }else{
        $query->whereHas('housetype', function($housetype){
          $housetype->where('development_id', request()->input('filter_development'));
        });
      }
    }

This then returns any plot where its housetype has a matching development_id for the filter_development from the request.

Thanks for everyone's input

Ad
source: stackoverflow.com
Ad