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

ThanhPv's avatar

Switch Between Roles of Multiple Roles User

Hi, I am sorry if this is not a good question. I am new to web app and Laravel too.

Is that a good ideas that make logged in user able to switch between role? and the best approach to do that in Laravel?

Thanks

0 likes
6 replies
Stratos's avatar

Why would you want to do that? The simplest way is to add a role column in your users table and define numbers for roles (1 = user, 2 = admin, 3 = superadmin, etc) then use middleware to check for each user's role.

With this approach, you could only change a user role by changing it in the DB so you need a function to do that for you.

ThanhPv's avatar

Thank @Stratos

A user may have multiple roles and I want that for each session the viewer is as one role and this cant make it easier to display views: or user is as Admin, or as Manager or as Editor, but only one role for a session.

I am thinking about something like $_SESSION['activeRole'], but I am not sure. Googling for this approach does not give me expected results.

Really appreciate if someone can help.

Stratos's avatar

If an user may have multiple roles then you might need a pivot table. Let your users table as usual, make a new Roles table and a pivot role_user table. That way you can assign many roles to the same user, and many users for the same role.

You don't need "activeRole", just look for all the roles associated for a given user, and display the views they have access to. So an Editor user that is also a Manager has access to editor view and access to manager view, because he's got both roles.

ThanhPv's avatar

Yes, I am using Entrust and having all those tables. What if I a have different dashboards for different roles, I do not want to display three dashboard for three-roles user. A user should choose one role in working session, or Manager or Admin or Editor then the views and actions are displayed and enabled accordingly. Eg: If he wants to work as Editor so switch to Editor role,

Stratos's avatar

Ah yes, I guess you could do that by verifying their current roles from DB, so if they belong to all 3 roles, they could choose to go into "editor role mode", save that variable in the session and display accordingly.

Please or to participate in this conversation.