|
8 | 8 | * @package Zizaco\Entrust |
9 | 9 | */ |
10 | 10 |
|
| 11 | +use Illuminate\Support\Facades\Cache; |
11 | 12 | use Illuminate\Support\Facades\Config; |
12 | 13 | use InvalidArgumentException; |
13 | 14 |
|
14 | 15 | trait EntrustUserTrait |
15 | 16 | { |
| 17 | + //Big block of caching functionality. |
| 18 | + public function cachedRoles() |
| 19 | + { |
| 20 | + $userPrimaryKey = $this->primaryKey; |
| 21 | + $cacheKey = 'entrust_roles_for_user_'.$this->$userPrimaryKey; |
| 22 | + return Cache::tags(Config::get('entrust.role_user_table'))->remember($cacheKey, Config::get('cache.ttl'), function () { |
| 23 | + return $this->roles()->get(); |
| 24 | + }); |
| 25 | + } |
| 26 | + public function save(array $options = []) |
| 27 | + { //both inserts and updates |
| 28 | + parent::save($options); |
| 29 | + Cache::tags(Config::get('entrust.role_user_table'))->flush(); |
| 30 | + } |
| 31 | + public function delete(array $options = []) |
| 32 | + { //soft or hard |
| 33 | + parent::delete($options); |
| 34 | + Cache::tags(Config::get('entrust.role_user_table'))->flush(); |
| 35 | + } |
| 36 | + public function restore() |
| 37 | + { //soft delete undo's |
| 38 | + parent::restore(); |
| 39 | + Cache::tags(Config::get('entrust.role_user_table'))->flush(); |
| 40 | + } |
| 41 | + |
16 | 42 | /** |
17 | 43 | * Many-to-Many relations with Role. |
18 | 44 | * |
@@ -69,7 +95,7 @@ public function hasRole($name, $requireAll = false) |
69 | 95 | // Return the value of $requireAll; |
70 | 96 | return $requireAll; |
71 | 97 | } else { |
72 | | - foreach ($this->roles as $role) { |
| 98 | + foreach ($this->cachedRoles() as $role) { |
73 | 99 | if ($role->name == $name) { |
74 | 100 | return true; |
75 | 101 | } |
@@ -105,9 +131,9 @@ public function can($permission, $requireAll = false) |
105 | 131 | // Return the value of $requireAll; |
106 | 132 | return $requireAll; |
107 | 133 | } else { |
108 | | - foreach ($this->roles as $role) { |
| 134 | + foreach ($this->cachedRoles() as $role) { |
109 | 135 | // Validate against the Permission table |
110 | | - foreach ($role->perms as $perm) { |
| 136 | + foreach ($role->cachedPermissions() as $perm) { |
111 | 137 | if (str_is( $permission, $perm->name) ) { |
112 | 138 | return true; |
113 | 139 | } |
|
0 commit comments