25
votes

I have three tables,

roles(id, name);
users(id, email, password);
user_role(id, user_id, role_id);

In this scenario, I have users table is associated to roles table with many to many relation.

I have two eloquent model as

Role
+users(){
    belongsToMany('User')
}

User
+roles(){
    belongsToMany('Role')
}

Now, the question is when I want to add a new user along with ids of roles that I would like to assign to users. How can I insert values to pivot table with Laravel best practices?

My existing code is:-

$roles = Input::get('roles'); // arrays of role ids

$user = new User();
$user->username = Input::get('username');
$user->password = Hash::make(Input::get('password'));
$user->save();

What to do next???

1

1 Answers

29
votes

It's really all described in the documentation.

Anyway, here's how you do it:

$user = new User();
$user->username = Input::get('username');
$user->password = Hash::make(Input::get('password'));
$user->save();
$user->roles()->attach($roles);

The important part is that you have to save the user before attaching (using attach()) the roles because otherwise the user doesn't have an id yet to be used in the pivot table.