entrust icon indicating copy to clipboard operation
entrust copied to clipboard

Correct way of checking for role?

Open resting opened this issue 8 years ago • 4 comments

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.

resting avatar Apr 22 '17 07:04 resting

were you able to solve this issue by any chance?

jaspalt avatar Jun 14 '17 19:06 jaspalt

I think that could be fixed by using View::share on boot(). So the auth user's role is queried just once

PaoloFalomo avatar Jun 14 '17 20:06 PaoloFalomo

@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.

resting avatar Jun 15 '17 01:06 resting

@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

PaoloFalomo avatar Jun 15 '17 07:06 PaoloFalomo