I am using my own implementation for user roles and permissions in laravel how to cache all the permissions and roles on user login and also to refresh the cache when new record is added. My tables are users ,roles, permissions,permission_role,permission_user,role_user. This is my table structure
i have created on of the provider and added this code to boot method
Permission::get()->map(function ($permission) { Gate::define($permission->name, function ($user) use ($permission) { return $user->hasPermission($permission); }); }); it is working fine but it is running the query each time which gets slowing down my application is there any way to cache all the permissions
here is my PermissionServiceProvider class
<?php namespace App\Providers; use Illuminate\Support\ServiceProvider; use Illuminate\Support\Facades\Gate; use Illuminate\Support\Facades\Schema; use Illuminate\Support\Facades\Blade; use App\Models\Permission; class PermissionServiceProvider extends ServiceProvider { /** * Bootstrap services. * * @return void */ public function boot() { if (Schema::hasTable('permissions')) { Permission::get()->map(function ($permission) { Gate::define($permission->name, function ($user) use ($permission) { return $user->hasPermission($permission); }); }); } Blade::directive('role', function ($role) { return "<?php if(Auth::user()->hasRole({$role})): ?>"; }); Blade::directive('endrole', function ($role) { return "<?php endif; ?>"; }); } /** * Register services. * * @return void */ public function register() { // } } and finally inside the user model
public function hasPermission($permission) { return $this->hasPermissionThroughRole($permission) || (bool) $this->permissions->where('name',$permission->name)->count(); } public function hasPermissionThroughRole($permission) { foreach($permission->roles as $role) { if($this->roles->contains($role)) { return true; } } return false; } and also here is my bit bucket repo
https://[email protected]/manojkiran/userrolesandpermissions.git
i have tried the method of @emtiaz-zahid https://stackoverflow.com/a/53511803/8487424 its working fine to cache all the permisisons in permissions table but is there any way to cahe all the permisisons and also the permissions to specifc user and role of the currently logged in user