Make conditional Eloquent relationship in Laravel

Viewed 196

Laravel 5.7. I have an Eloquent model Theme, with two fields, id and name.

Another model, Filter, has three fields: id, name, theme_id.

Filter:

class Filter extends Model
{
    public function theme()
    {
        return $this->belongsTo('App\Theme');
    }
}

I can attach these filters to an arbitrary number of other models, e.g. the model Foo has two fields, id and name. I attach the filter to it using a Filterables table:

Filterables:

id | filter_id | filterable_id | filterable_type
------------------------------------------------
1  |  1        |  3            |  App\Foo

The above example shows that the Filter of id 1 is attached to the Foo of id 3.

Now to get all the filters of Foo, I have this relationship in my Foo model:

Foo:

class Foo extends Model
{
    public function filters()
    {
        return $this->morphToMany('App\Filter', 'filterable');
    }
}

This all works fine. But now I want to get the Foo model, and only the filters where the filter's theme_id is (for example) 1.

How can I add this condition to the filters relationship?

1 Answers

Just add a where clause directly to your relationship

class Foo extends Model
{
    public function filters()
    {
        return $this->morphToMany('App\Filter', 'filterable')->where('theme_id', 1);
    }
}
Related