创建用户附加标准角色时

时间:2017-12-03 11:02:21

标签: php laravel

我正在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函数并附加具有指定标准角色的用户的任何建议吗?

感谢您的回复!

1 个答案:

答案 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());