user3743266
user3743266

Reputation: 1172

Laravel belongsToMany only works one way

I'm trying to make a many to many relation, in this example with user and role.

In User model I got this:

public function roles()
{
    return $this->belongsToMany('App\Role', 'user_role', 'user_id', 'role_id');
}

In Role model I got this:

public function users()
{
    return $this->belongsToMany('App\User', 'user_role', 'role_id', 'user_id');
}

And my pivot table user_role:

public function up()
    {
        Schema::create('user_role', function(Blueprint $table) {
            $table->increments('id');
            $table->integer('user_id')->unsigned();
            $table->integer('role_id')->unsigned();
            $table->timestamps();

            $table->foreign('role_id')->references('id')->on('roles');
            $table->foreign('user_id')->references('id')->on('users');
        });
    }

Now when I do $user->roles()->attach(1); it makes a row in the user_role table. But the problem is when I want to access it: $user->roles; it returns nothing. It works with $role->users; but not the other way. What am I doing wrong?

Upvotes: 2

Views: 730

Answers (2)

Denis Mitrofanov
Denis Mitrofanov

Reputation: 5

You have to reload the relationship after attaching like so

$user->roles()->attach($role);

$user->load('roles');

Upvotes: 0

Hashmat Waziri
Hashmat Waziri

Reputation: 477

Solved : Laravel 5.2.29

make sure the table name is role_user

    $user = User::find(1);
    $role = Role::find(2);
    // In this example I am passing in a Role object but $role->id also works
    $user->roles()->attach($role);

Hope this works for you.

Upvotes: 1

Related Questions