Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

maneeshpatel's avatar

How to access Modals associated to a Tag using n-TO-n Polymorhpism in Laravel.

For tagging my Quizzes, Notes I am using Github package https://github.com/cviebrock/eloquent-taggable. Its working fine.

Table Details-

Quizzes
    id - integer
    name - string

Notes
    id - integer
    name - string

Tags
    id - integer
    name - string

Tagged
    tag_id - integer
    taggable_id - integer
    taggable_type - string

Tag Modal:-

class Tag extends Eloquent {
    public function taggable()
    {
        return $this->morphTo();
    }
}

Notes Modal :-

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

Quiz Model:-

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

Taggable Trait :-

trait Taggable
{
    public function tags()
    {
        return $this->morphToMany('App\Tag', 'taggable', 'tagged', 'taggable_id', 'tag_id);
    }
}

With this setup I am able to add tags to my notes or quizzes . And also can fetch tags of a notes or quiz.

Add tag to model

$model->tag('Apple,Banana,Cherry');

access tag of a model

foreach($model->tags as $tag)
{
    echo $tag->name;
}

But if I want to access all Quizzes or Notes from a tag, I am getting NULL.

Tried Code

    $tag = App\Tag::findByName('quizcanvas 1');
    $taggable_types = $tag->taggable();
    dd($taggable_types);

Is there any way to fetch Quizzes or Notes associated to any Tag?

0 likes
0 replies

Please or to participate in this conversation.