Roles / Permissions Slow #2730
Replies: 2 comments 1 reply
-
Can you provide some context about the quantity and complexity of roles and permissions in your app? The hardest thing about diagnosing a slowdown scenario is in recreating that scenario for analysis and testing. It would be super helpful if you can provide a simple app which exhibits the same problem. Then it's easier to explore what's actually in cache and in the queries and where queries might be inefficient. |
Beta Was this translation helpful? Give feedback.
-
Thank you for the additional information. It led me down a path that realized that the delay wasn't a database query. That query was being cached. The issue was the looping though every role + permission on every load. So ultimately I fixed this problem by setting in the permissions config file:
and adding this in my AuthServiceProvider to do the check. Gate::before(function ($user, $ability) {
// Attempt to get the cached roles and permissions
$rolesAndPermissions = Cache::get("user_roles_permissions_{$user->id}");
// If cache is not set, call the required methods to populate it
if (!$rolesAndPermissions) {
// Fetch roles and permissions
$rolesAndPermissions = [
'roles' => $user->getRoleNames(),
'permissions' => $user->getAllPermissions()->pluck('name')
];
// Store in cache for future use
Cache::put("user_roles_permissions_{$user->id}", $rolesAndPermissions, 60 * 60);
}
// Allow access if the user has the required permission
if ($rolesAndPermissions['permissions']->contains($ability)) {
return true;
}
return null;
}); |
Beta Was this translation helpful? Give feedback.
-
Hi all,
I know this topic has been covered a number of times. I have a fix in place, but I need help completing the adjustment.
In my AuthServiceProvider.php boot I have added the following:
This code does an amazing job of reducing the load times dramatically.
The issue, is the first load.
In order for this to work the User model must have
But keeping that available after the first cache negates any speed increase. I need to be able to utilize those functions once and then avoid and let the other mechanism perform the role / permission check.
Can anyone add insight or an alternative way to the current implementation. To demonstrate the severity of this issue, here are screenshots of timing. The only difference is commenting out
use HasRoles
after cached. It's dramatic.With caching and commenting out User - HasRoles
Without caching
Any help or insight is greatly appreciated!
Beta Was this translation helpful? Give feedback.
All reactions