Replies: 3 comments
-
Release 4.3.0 updates caching approaches |
Beta Was this translation helpful? Give feedback.
-
The problem with that is when you has a lot of users, you gonna have a lot of cache keys, they tried something like that once, also it needs a forget especific user cache with unique key, example
Maybe because laravel-permission/src/Models/Role.php Lines 15 to 17 in 78eaa5e laravel-permission/src/PermissionRegistrar.php Lines 121 to 123 in 78eaa5e |
Beta Was this translation helpful? Give feedback.
-
@drbyte maybe this can be an optional trait for the User's model on the package, i could make a PR, what do you think?
@moisish maybe https://stackoverflow.com/a/56263511 can help you for that, only add on use Illuminate\Database\Eloquent\Collection;
use Spatie\Permission\PermissionRegistrar;
///****///
protected function getPermissionCacheKey(string $relation): string {
return sprintf(PermissionRegistrar::$cacheKey.'.'.str_replace('\\','.',$this->getMorphClass()).'.%d.'.$relation, $this->getKey());
}
private function getCachedPermissions(string $relation): Collection {
if ($this->relationLoaded($relation)) {
return $this->getRelationValue($relation);
}
$class = $relation === 'roles' ? app(PermissionRegistrar::class)->getRoleClass() : app(PermissionRegistrar::class)->getPermissionClass();
$array = \Cache::remember($this->getPermissionCacheKey($relation), config('session.lifetime', 120) * 60, function () use($relation) {
return $this->getRelationValue($relation)->map(function($data){
return ['i' => $data->id, 'n' => $data->name, 'g' => $data->guard_name];
})->all();
});
$collection = $class::hydrate(
collect($array)->map(function ($item) { return ['id' => $item['i'], 'name' => $item['n'], 'guard_name' => $item['g']]; })->all()
);
$this->setRelation($relation, $collection);
return $collection;
}
public function getRolesAttribute(): Collection {
return $this->getCachedPermissions('roles');
}
public function getPermissionsAttribute(): Collection {
return $this->getCachedPermissions('permissions');
}
public function forgetAssignedPermissions(): bool {
return \Cache::forget($this->getPermissionCacheKey('roles')) && \Cache::forget($this->getPermissionCacheKey('permissions'));
} NOTE: Don´t forget call |
Beta Was this translation helpful? Give feedback.
-
Hello,
From what I can see there is caching on the PermissionRegistrar class which caches all the available permissions and roles on the property $permissions.
What about caching the User's permissions so everytime you use the
hasPermissionTo
method is not running a query against the DB?Otherwise why does the cache gets cleared on the methods givePermissionTo, revokePermissions etc if the user's permissions are not cached?
Beta Was this translation helpful? Give feedback.
All reactions