3

I have 3 tables

User(id,name,email)
Role(id,rolename)
role_user(user_id,role_id)

In roles table i have following data;

id    rolename
1     admin
2     user 

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

I have one eloquent model as

UserModel
 user_roles(){
belongsToMany('Role')
 }

Now I want to save data in role_user table when i create user. I have roles in dropdown.

I am using following query

$user = new User();
$user->username = $data->username;
$user->email= $data->email
$user->save();

its perfectly saves the user in user table but i want also want to save data in user_role table.

Can you guys please help me how to save this ??

Tiago Martins Peres
  • 14,289
  • 18
  • 86
  • 145
Hani Mehdi
  • 187
  • 4
  • 9

2 Answers2

3

Use attach() method after you create the user:

$user->roles()->attach($roleId);
Alexey Mezenin
  • 158,981
  • 26
  • 290
  • 279
0

In User model:

public function roles()
{
    return $this->belongsToMany(Role::class);
}

In Role model:

public function users()
{
    return $this->belongsToMany(User::class);
}

I assume you pass the roles as an array, then in your controller you can have something like this:

public function store(Request $request)
{
    //return $request->roles;
    $this->validate($request, [
        'name'  => 'required|string',
        'email' => 'required|email|unique:users',
        'password'  => 'required|confirmed'
    ]);

    $user = new User();
    $user->name = $request->name;
    $user->email = $request->email;
    $user->password = $request->password;

    $user->save();

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

    return redirect()->route('backend.users');
}
Rouhollah Mazarei
  • 3,969
  • 1
  • 14
  • 20