How to set a role for a new User when one is joining.
Closed this issue · 2 comments
bamboowebcare commented
How to set a role for a new User when one is joining.
tortuetorche commented
Hi @bamboowebcare,
You can do this:
class User extends Model
{
// ...
public function hasRole($key)
{
$hasRole = false;
foreach ($this->roles as $role) {
if ($role->name === $key) {
$hasRole = true;
break;
}
}
return $hasRole;
}
public function attachRoles($roles = [])
{
$roles = (array) $roles;
// Default role is 'user'
// You can comment out this code, if you don't want default role
if (! in_array('user', $roles)) {
$roles = array_merge($roles, ['user']);
}
foreach ($roles as $roleName) {
if (! $this->hasRole($roleName)) {
$role = Role::where('name', $roleName)->firstOrFail();
$this->roles()->attach($role);
}
}
}
//...
}
$adminUser = User::create([
'email' => 'admin@localhost.com',
'firstname' => 'Super',
'lastname' => 'Admin',
'password' => 'superpassword',
]);
// Add 'admin' and 'user' roles to the administrator user
$adminUser->attachRoles(['admin', 'user']);
Have a good day,
Tortue Torche
bamboowebcare commented
thank you