ToxifiedHashkey
ToxifiedHashkey

Reputation: 267

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.

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);
}
public function toResponse($request)
{
    if(Auth::user()->hasAnyRoles(['administrator', 'employee'])) {
        return redirect()->route('backend.dashboard');
    }

    return redirect()->route('frontend.dashboard');
}

Upvotes: 0

Views: 1770

Answers (2)

MrEduar
MrEduar

Reputation: 1986

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

Upvotes: 0

lagbox
lagbox

Reputation: 50561

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

Upvotes: 0

Related Questions