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

Kaustubh's avatar

Show/Hide pages dynamically based on ROLES

Hi, I created roles and i want to assign pages based on its roles ie. admin can view all pages and customer can view 4 pages, but in my system there can be more roles in future so i don't want to code every time when i create new roles.

I made a page where i can select role and assign pages to that roles, but i am getting problem to achieve this because i don't know how to restrict other roles to access this page.

-- the original way is like this
 
@if ( Auth::check() && Auth::user()->isAdmin() )
  ...
@endif 

-- but my roles can be change every time and i don't want to code again and again

i need your help to achieve this

0 likes
4 replies
zachleigh's avatar

Instead of an isAdmin method, how about an hasRole method?

Auth::user()->hasRole(['admin', 'moderator' ])
Kaustubh's avatar

@zachleigh

i have role table in which i can add more roles. so every time when i will add role i have to mention in my code and i dont want to code in that.

Just like when i create role from my view. i will select pages so that particular role can view that page.

topvillas's avatar

If you're restricting access to whole pages and not just sections of pages you're better off writing your own has role middleware.

There's no getting around the fact that you're going to have change something when you add a new role but with middleware and parameters, at least your changing configuration and not code.

1 like
zachleigh's avatar

Do it all in the database and make a web front end for it. In the db, associate roles with uri strings. Then check for the roles in middleware.

1 like

Please or to participate in this conversation.