Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
274 views
in Technique[技术] by (71.8m points)

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 between users and roles so I am unable to check the role from an array of roles.

  • Database Structure
Users
---------------
* id
* name
* email
* password
* role_id
* created_at

Roles
---------------
 * id
 * name
 * slug
 * created_at
  • 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
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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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;
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...