On every page of the application the Laravel debugger shows that the follow two queries is running. Roles and Permissions have not changed so often and i want to cache these queries. Can you please let me know how can i do so?
select `roles`.*, `model_has_roles`.`model_id` as `pivot_model_id`, `model_has_roles`.`role_id` as `pivot_role_id`, `model_has_roles`.`model_type` as `pivot_model_type` from `roles` inner join `model_has_roles` on `roles`.`id` = `model_has_roles`.`role_id` where `model_has_roles`.`model_id` = 1 and `model_has_roles`.`model_type` = 'App\Models\User'
select `permissions`.*, `model_has_permissions`.`model_id` as `pivot_model_id`, `model_has_permissions`.`permission_id` as `pivot_permission_id`, `model_has_permissions`.`model_type` as `pivot_model_type` from `permissions` inner join `model_has_permissions` on `permissions`.`id` = `model_has_permissions`.`permission_id` where `model_has_permissions`.`model_id` = 1 and `model_has_permissions`.`model_type` = 'App\Models\User'
anyone have any solution for the issue i am facing here?
I used Eloquent Accessors which override this methods ( roles and permissions )
Maybe this is not the best solution, but I did not find another. :)
// User.php
use Spatie\Permission\Models\Role;
use Spatie\Permission\Models\Permission;
class User {
// Cache permissions and roles
public function getPermissionsAttribute() {
$permissions = Cache::rememberForever('permissions_cache', function() {
return Permission::select('permissions.*', 'model_has_permissions.*')
->join('model_has_permissions', 'permissions.id', '=', 'model_has_permissions.permission_id')
->get();
});
return $permissions->where('model_id', $this->id);
}
public function getRolesAttribute() {
$roles = Cache::rememberForever('roles_cache', function () {
return Role::select('roles.*', 'model_has_roles.*')
->join('model_has_roles', 'roles.id', '=', 'model_has_roles.role_id')
->get();
});
return $roles->where('model_id', $this->id);
}
}
Sorry for my English -_-
Thank you for posting a solution. I hope many other will be benefited by your code.
Dear contributor,
because this issue seems to be inactive for quite some time now, I've automatically closed it. If you feel this issue deserves some attention from my human colleagues feel free to reopen it.
Most helpful comment
I used Eloquent Accessors which override this methods ( roles and permissions )
Maybe this is not the best solution, but I did not find another. :)
Sorry for my English -_-