I am successfully able to check if the user has a single role. Now what I need here to check is, if the user is either an administrator or an employee, and if any of the above role matches then return true else false. I am unable to do so as I am using one to many relationship between users
and roles
so I am unable to check the role from an array of roles.
Users
---------------
* id
* name
* email
* password
* role_id
* created_at
Roles
---------------
* id
* name
* slug
* created_at
public function role()
{
return $this->belongsTo(Role::class);
}
public function hasRole(string $role)
{
if ($this->role()->where('slug', $role)->exists()) {
return true;
}
return false;
}
public function hasAnyRoles(array $roles)
{
if ($this->role()->whereIn('slug', $roles)->exists()) {
return true;
}
return false;
}
public function users()
{
return $this->hasMany(User::class);
}
- App/Http/Responses/LoginResponse
public function toResponse($request)
{
if(Auth::user()->hasAnyRoles(['administrator', 'employee'])) {
return redirect()->route('backend.dashboard');
}
return redirect()->route('frontend.dashboard');
}
question from:
https://stackoverflow.com/questions/65945365/how-to-check-for-a-role-from-an-array-of-roles-and-return-true-if-any-of-the-rol 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…