1 year ago

Trouble with defining relationships

Posted 1 year ago by timgavin

I'm having a hard time figuring out the relationships between my tags and posts.

I created a tagging system that would store tags in one table (tags) and the posts that use them in another (tags_posts).

What I want to do is get the tags when getting the posts by doing this: $post = Post::with('tags')->find(1); instead of something like this: $post = Post::with('tags.tags')->find(1);

So far all I've been able to do is get the tag IDs from the TagPost relationship and scratch my head a lot.

I tried a hasManyThrough relationship but that didn't work out too well. I'm kind of stuck here...

Schema::create('tags', function (Blueprint $table) {

Schema::create('tags_posts', function (Blueprint $table) {
    $table->unique(['tag_id', 'post_id']);


public function tags()
    return $this->hasMany(TagPost::class, 'post_id');

// tried this with no success
public function tags()
    return $this->hasManyThrough('App\Tag', 'App\TagPost', 'post_id', 'tag_id);


public function tags()
    return $this->belongsToMany('App\Tag');

Hopefully this makes sense!

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