我正在laravel 5.5应用程序中创建一个User,如下所示:
return User::create([
'name' => $data['name'],
'email' => $data['email'],
'password' => bcrypt($data['password']),
]);
我正在使用链接表user_role
向用户添加角色。
过去我曾使用attach
向用户添加角色,如下所示:
$user = new User();
$user->email = $request['email'];
$user->password = $request['password'];
$user->save();
$user->roles()->attach(Role::where('name', 'User')->first());
有关如何将attach
添加到User::create
函数并附加具有指定标准角色的用户的任何建议吗?
感谢您的回复!
答案 0 :(得分:2)
如果create
成功创建了一个用户,则可以根据该方法调用roles()
:
$user = User::create([
'name' => $data['name'],
'email' => $data['email'],
'password' => bcrypt($data['password']),
]);
$user->roles()->attach(Role::where('name', 'User')->first());
return $user
或
return User::create([
'name' => $data['name'],
'email' => $data['email'],
'password' => bcrypt($data['password']),
])->roles()->attach(Role::where('name', 'User')->first());