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?

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 betweenusers
androles
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
Answer
Answer
Solution:
You could usein_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;
}
Share solution ↓
Additional Information:
Link To Answer People are also looking for solutions of the problem: closed without sending a request; it was probably just an unused speculative preconnection
Didn't find the answer?
Our community is visited by hundreds of web development professionals every day. Ask your question and get a quick answer for free.
Similar questions
Find the answer in similar questions on our website.
Write quick answer
Do you know the answer to this question? Write a quick response to it. With your help, we will make our community stronger.