5 years ago

Polymorphic Many To Many

Posted 5 years ago by grit


Under the heading "Many To Many Polymorphic Relations" in the laravel docs

This bit is fine and working.

class Post extends Eloquent {
    public function tags()
        return $this->morphToMany('Tag', 'taggable');

With the tag model, I would like to get all related models, the same way as I can with morphTo.

class Tag extends Eloquent {

    // Not sure what to do here?
    public function taggable()
        return $this->{?????}('All Models', 'taggable');

    public function posts()
        return $this->morphedByMany('Post', 'taggable');

    public function videos()
        return $this->morphedByMany('Video', 'taggable');

The only way I can think of at the moment of achieving this would be to create a model called Taggable and doing a hasMany relationship from Tag to Taggable then a morphTo relationship from taggable to all related models. That doesn't seem right to me though and think I might be missing a trick. Some help would be really great.

Please sign in or create an account to participate in this conversation.