You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
 
 

70 lines
1.5 KiB

<?php
namespace App\Entities\Users;
trait HasRoles
{
/**
* A user may have multiple roles.
*
* @return \Illuminate\Database\Eloquent\Relations\BelongsToMany
*/
public function roles()
{
return $this->belongsToMany(Role::class);
}
/**
* Assign the given role to the user.
*
* @param string $role
* @return mixed
*/
public function assignRole($role)
{
return $this->roles()->save(
Role::whereName($role)->firstOrFail()
);
}
/**
* Determine if the user has the given role.
*
* @param mixed $role
* @return boolean
*/
public function hasRole($role)
{
if (is_string($role)) {
return $this->roles->contains('name', $role);
}
return !! $role->intersect($this->roles)->count();
}
/**
* Determine if the user may perform the given permission.
*
* @param Permission $permission
* @return boolean
*/
public function hasPermission(Permission $permission)
{
return $this->hasRole($permission->roles);
}
public function hasRoles(array $roleNameArray)
{
return $this->roles->contains(function($key, $role) use ($roleNameArray) {
return in_array($role->name, $roleNameArray);
});
}
public function scopeHasRoles($query, array $roleNameArray)
{
return $query->whereHas('roles', function($q) use ($roleNameArray) {
$q->whereIn('name',$roleNameArray);
});
}
}