Search code examples
phpdatabaselaravelmany-to-manylaravel-5.6

Laravel 5.6: Many-to-many relationship returns empty object


I'm setting up a many-to-many relationship in Laravel 5.6 models but, since I'm not following Laravel's naming convention, I'm surely making a mistake on table/foreign keys name that makes it not working.

My tables related to the blog section all have a blog_ prefix:

  1. blog_posts collects all posts info (id, title, article, etc.)
  2. blog_tags defines the tags that can be used to tag the post (id, name)
  3. blog_posts_tags is the pivot table that creates the relationships between posts and tags (id, post_id, tag_id)

As said, I'm trying to set up the relationships in Laravel:

Model: BlogPost.php

/**
 * The tags that belong to the post.
 */
public function tags()
{
    return $this->belongsToMany('App\BlogTag', 'blog_posts_tags', 'post_id', 'tag_id'); 
}

Model: BlogTag.php

/**
 * The posts that belong to the tag.
 */
public function posts()
{
    return $this->belongsToMany('App\BlogPost', 'blog_posts_tags', 'tag_id', 'post_id');
}

The problem is that, when I call tags() method, the returned object hasn't the tags inside:

$post = BlogPost::find($id);
$tags = $post->tags();

Where am I wrong?


Solution

  • $post->tags() returns you releated instance with query builder.

    if you want to get releated tag values, just use name of relation

    example: $tags = $post->tags;

    foreach($tags as $tag){
       var_dump($tag);
    }