laravelpolymorphic-associationsrelationships

Laravel Specifying a condition for a morphMany collection


I have the following Eloquent relationship

class Broker extends Eloquent{

    public function configurable(){
        return $this->morphTo();
    }
}

class ProductConfiguration extends Eloquent{

    public function productConfigurations()
    {
        return $this->morphMany('Excel\Products\ProductConfiguration','configurable');
    }
}

I can very easily find all the ProductConfigurations that belong to a Broker by doing this:

    $broker = Broker::find($id);
    $productConfigurations = $broker->productConfigurations;

What I am unclear about though is how to specify conditions for the ProductConfigurations, so if my ProductConfiguration has a type field, something like:

    $broker = Broker::find($id);
    $productConfigurations = $broker->productConfigurations->where('type' = 'reg');

Checking the documentation I can't exactly find how to do that.


Solution

  • Ok, must just have had a temporary brain freeze or something, it was as easy as this:

    $broker = Broker::find($id);    
    $configurations = $broker->productConfigurations()
         ->where('type',$type)
         ->get();