Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

vincent15000's avatar

Best pratice to check user roles inside a policy

Hello,

I have a policy looking like this.

public function delete(User $user, Room $room)
{
    return Role::where('collaborator_id', $user->current_collaborator_id)->whereIn('role', [0, 1])->exists() && $room->company_id == session('current_company_id') && $room->courses_count == 0;
}

When I retrieve the list of all rooms, I send the datas to VueJS via InertiaJS with rights datas (update rights and delete rights for each line).

That means that if I have 10 rooms to display, I call 20 times the room query to check the rights.

That's really not the good way.

Each user has one or many roles for a company. I thought about storing the roles of the connected user in the session, but is it secure enough to store the roles in the session ? That's mean each time I need to check a role, I only retrieve it in the session without checking the roles in the database.

So what'is the best way to check the roles in the policies ?

Can you help me ?

Thank you.

V

0 likes
2 replies
vincent15000's avatar

I have this idea to improve my policies. What about adding an edit method in the policy ?

public function edit(User $user, Room $room)
{
    return (in_array(0, session('roles')) || in_array(4, session('roles'))) && $room->company_id == session('current_company_id');
}

public function update(User $user, Room $room)
{
    return Role::where('collaborator_id', $user->current_collaborator_id)->whereIn('role', [0, 1])->exists() && $room->company_id == session('current_company_id');
}

Check the roles from the session just to display the menus, disable the buttons, ...

But for real update in the database, I retrieve all roles directly from the database.

Is it a good idea to do that ?

vincent15000's avatar
vincent15000
OP
Best Answer
Level 63

Here is what I have done.

I have added a middleware to the routes which need it. Thus this middleware is executed each time a request is done. It retrieves the different datas : roles, current_company_id, ... and put them in the session. Then I send these datas to the front as InertiaJS shared datas (essentially to hide some menus and buttons according to the roles).

In the backend, the policies use the session datas to check if a user can or cannot do an action. As the session datas are refreshed at each request via the middleware, I think that's it's secure enough to do like that.

If you want to comment this or help me to understand that it's perhaps not secure enough, don't hesitate.

Now that I have done all this code, I wonder if it would not be a better idea to use some package like Spatie roles and permissions. I never used it but I know that it's a good package.

Please or to participate in this conversation.