php - How to check for a role from an array of roles and return true if any of the role exists, for one to many relationship? ← (PHP)
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.
- Database Structure
Users
- App/Models/User
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;
}
- App/Models/Role
public function users()
{
return $this->hasMany(User::class);
}
- App/Http/Responses/LoginResponse
{-code-6}
Answer
----- * id * name * email * password * role_id * created_at Roles
Answer
----- * 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); }|||public function toResponse($request) { if(Auth::user()->hasAnyRoles(['administrator', 'employee'])) { return redirect()->route('backend.dashboard'); } return redirect()->route('frontend.dashboard'); }
Answer
Solution:
You could use in_array
to see if the slug of the role assigned is in the array you are passing:
public function hasAnyRoles(array $roles)
{
if ($this->role) {
return in_array($this->role->slug, $roles);
}
return false;
}
Answer
Solution:
Because it is a one-to-many inverse relationship you cannot do whereIn. Instead you can use this.
public function role()
{
return $this->belongsTo(Role::class);
}
public function hasRole(string $role)
{
return $this->role()->where('slug', $role)->exists();
}
public function hasAnyRoles(array $roles)
{
if (is_array($roles)) {
foreach ($roles as $role) {
if ($this->hasRole($role)) {
return true;
}
}
}
return false;
}