Skip to content

Instantly share code, notes, and snippets.

@iDevelopThings
Last active November 9, 2017 22:27
Show Gist options
  • Save iDevelopThings/15a9e638a3696f5ccfd77c1246a05153 to your computer and use it in GitHub Desktop.
Save iDevelopThings/15a9e638a3696f5ccfd77c1246a05153 to your computer and use it in GitHub Desktop.
Allows you to add roles to a laravel user
<?php
namespace App\Support\Traits;
use App\Role;
use App\UserRole;
trait HasRoles
{
/*
* Relation to getuser roles
*/
public function userRoles()
{
return $this->hasMany(UserRole::class)->with('role');
}
/**
* Flush the cache
*/
private function flushCache()
{
\Cache::forget("user.{$this->id}.roles");
}
/**
* Get all user roles
*
* @return mixed
*/
public function roles()
{
$roles = \Cache::remember("user.{$this->id}.roles", 60, function () {
$userRoles = $this->userRoles()->get();
if (!$userRoles->first()) {
return null;
}
$rolesFormatted = $userRoles->map(function ($value) {
return $this->formatRole($value);
});
return $rolesFormatted->toArray();
});
return $roles;
}
/**
* Check if the user has a role
*
* @param $role
*
* @return bool
*/
public function hasRole($role)
{
$roles = collect($this->roles());
if ($roles->where('role', $role)->first()) {
return true;
}
return false;
}
/**
* Check if the user has multiple roles
*
* @param array $roles
*
* @return bool
*/
public function hasRoles($roles = [])
{
$userRoles = collect($this->roles());
foreach ($roles as $role) {
if (!$userRoles->where('role', $role)->first()) {
return false;
}
}
return true;
}
/**
* Add a role to the user
*
* @param $role
*
* @return bool
*/
public function addRole($role)
{
if ($this->hasRole($role)) {
return true;
}
$userRole = new UserRole;
$userRole->user_id = $this->id;
$userRole->role_id = Role::where('name', $role)->first()->id;
$userRole->save();
$this->flushCache();
$this->userRoles();
return true;
}
/**
* Remove a role from the user
*
* @param $role
*
* @return bool
*/
public function removeRole($role)
{
if (!$this->hasRole($role)) {
return true;
}
$roleToRemove = Role::where('name', $role)->first();
if (!$roleToRemove) {
return false;
}
$this->userRoles()->where('role_id', $roleToRemove->id)->delete();
$this->flushCache();
$this->userRoles();
return true;
}
/**
* Format a role instance
*
* @param $role
*
* @return array
*/
private function formatRole($role)
{
return [
'id' => $role->id,
'role_id' => $role->role->id,
'title' => $role->role->title,
'role' => $role->role->name,
];
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment