You have few techniques, like:
- Grouping permissions.
For example, if multiple roles have the same "edit_post" permission, you can define a single gate for "edit_post" and check if the user has any role that grants this permission.
- Dynamic gate definitions
Instead of defining gates for all permissions during middleware execution, you can define gates dynamically when they are actually needed. This reduces the number of gates loaded into memory at once.
class AuthGates
{
public function handle($request, Closure $next)
{
$user = auth()->user();
if ($user) {
$permissions = $this->getUserPermissions($user);
foreach ($permissions as $permission) {
Gate::define($permission->title, function (User $user) use ($permission) {
return $user->hasPermission($permission);
});
}
}
return $next($request);
}
protected function getUserPermissions(User $user)
{
$cacheKey = 'user_permissions_' . $user->id;
return Cache::remember($cacheKey, now()->addMinutes(3), function () use ($user) {
// Fetch and return the user's permissions here
});
}
}