Laravel Many-To-Many relation returns no results

I am currently learning Laravel and I have an issue which I can't seem to find a solution for. I have a many-to-many relation between two tables that always returns nothing. Let me show you the basic setup:

My posts Model:

// App\Post.php
protected $fillable = [
    'name',
    'description'
    'videopath'
];

public function Tags()
{
    return $this->belongsToMany('App\Tag');
}
public function Cats()
{
    return $this->belongsToMany('App\Cat');
}

My tags model:

// App\Tag.php
protected $fillable = [
    'name',
    'description'
];

public function exercises()
{
    return $this->belongsToMany('App\Exercise');
}

My posts controller:

// PostController.php
public function show($id)
{
    $post = Post::find($id);
    return view('posts', ['post'=>$post];
}

The view:

// posts.blade.php
@foreach($post->tags() as $tag)
    //do stuff
@endforeach

The intermediate table is called post_tag and contains the post_id and tag_id columns. At first it returned the results as expected but after some while all of my posts didn't return any tags anymore. The cats model looks similar to the tags model. Anyone has an idea?

2 answers

  • answered 2017-11-12 20:55 HCK

    1. Check the name of your Tags function. In your view you are calling "tags" instead of "Tags".

    2. Have you created the intermediate table in your database? If so, check the naming convention (alphabetic order) that Laravel uses to find it: in your case it should be tag_post. if not, customize the name of the table when defining the relationship.

    Many To Many

    Many-to-many relations are slightly more complicated than hasOne and hasMany relationships. An example of such a relationship is a user with many roles, where the roles are also shared by other users. For example, many users may have the role of "Admin". To define this relationship, three database tables are needed: users, roles, and role_user. The role_user table is derived from the alphabetical order of the related model names, and contains the user_id and role_id columns.

  • answered 2017-11-12 21:15 Lance Pioch

    Taking your view:

    @foreach($post->tags() as $tag)
        //do stuff
    @endforeach
    

    $post->tags() will return the relationship instead of the actual collection. You want $post->tags instead or $post->tags()->get().