我正在使用 https://github.com/romanbican/roles 来管理用户角色。我正在尝试将用户的角色设置为现有角色。
我可以通过以下方式创建新角色:
$role = Role::create([
'name' => 'Admin',
'slug' => 'admin'
]);
$user = User::find($id)->attachRole($role);
这工作正常。问题在于将角色设置为现有角色。有接受 id 的attachRole
方法。我承担了角色的 ID。如果我能做attachRole('admin');
那就太好
文档中如何执行此操作不是很清楚。我尝试再次简单地创建角色,但正如预期的那样,我收到重复的角色错误。对不起,如果这是一个菜鸟问题,我昨天刚开始使用 L5。
我不知道
包,但您应该能够检索角色模型并使用它:
$role = Role::where('slug', 'admin')->first();
$user = User::find($id)
if($role && $user){
$user->attachRole($role);
}
else {
// either role or user not found
}