entrust
entrust copied to clipboard
Correct way of checking for role?
I've been using this method of checking for role Auth::user()->hasRole('admin'), throughout my layout and view files.
It was only until I installed Laravel Debugbar that I realise there were multiple repeated database queries. For instance, 19 statements were executed, 18 of which were duplicated, 1 unique
Most of them were:
select `roles`.*, `role_user`.`user_id` as `pivot_user_id`, `role_user`.`role_id` as `pivot_role_id` from `roles` inner join `role_user` on `roles`.`id` = `role_user`.`role_id` where `role_user`.`user_id` = '1'
Removing hasRole() has helped to reduce the queries.
So I guess probably shouldn't be doing checks this way.
What is the correct way of checking for roles?
I found Blade Templates directives to be a cleaner solution, but it doesn't seem to help reduce the queries.
were you able to solve this issue by any chance?
I think that could be fixed by using View::share on boot(). So the auth user's role is queried just once
@jaspalt No. Each time you check for roles or permissions one or more query is/are made. One workaround I can think of is to do it once, store the result in a variable as boolean and use that instead.
@jaspalt take a look at this https://laravel.com/docs/5.4/views#passing-data-to-views to pass a variable to each view like suggested by @resting