Last active
November 3, 2017 19:21
-
-
Save sayhicoelho/96e5ce0a13719c8e4c55c75614837431 to your computer and use it in GitHub Desktop.
Trait to manage user ACL
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
namespace App\Traits; | |
trait CheckRole | |
{ | |
/** | |
* The roles that belong to the user. | |
*/ | |
public function roles() | |
{ | |
return $this->belongsToMany(\App\Role::class); | |
} | |
/** | |
* Check whether user has any role. | |
* | |
* @param string|array $roles | |
* @return boolean | |
*/ | |
public function hasAnyRole($roles) | |
{ | |
if (is_array($roles)) | |
{ | |
foreach ($roles as $role) | |
{ | |
if ($this->hasRole($role)) | |
{ | |
return true; | |
} | |
} | |
} | |
else if ($this->hasRole($roles)) | |
{ | |
return true; | |
} | |
return false; | |
} | |
/** | |
* Check whether user has a role. | |
* | |
* @param string $role | |
* @return boolean | |
*/ | |
public function hasRole($role) | |
{ | |
if ($this->roles()->whereSlug($role)->first()) | |
{ | |
return true; | |
} | |
return false; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment