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

eleven0's avatar

@can('role') condition based on Roles instead of permissions

I followed this (https://laracasts.com/series/whats-new-in-laravel-5-1/episodes/16), tutorial and built a user authorization system.

in blade template file, how can I set a condition for a role name or id instead of a permission name. (i have a lot of permissions, but only 5 user roles, easier for me to build my pages according to roles names or ids).

@can('manager') //users with manager role can access this area.... @endcan

How do I register a policy for that?

Currently, the system works when I specify @can condition with a permission name.

Thanks.

0 likes
4 replies
rawilk's avatar

Why not just make another blade directive for role?

@role('manager')
    // users with manager role can access this area....
@endrole
D9705996's avatar
D9705996
Best Answer
Level 51

Add this to your appserviceprovider boot() to only show the contents to the user if the are logged in and they have a role

Blade::if('role', function ($name) {
        return auth()->check() && auth()-user()->hasRole($name);
});

You will need to implement hasRole($name) on your user model to fit your needs

You can then use this in your views

@role('manager')
   // manager view specifics
@endrole
eleven0's avatar

thanks guys , that worked out great!

If I wanted to give access to multiple roles for that same section, how can I set that up through blade ? Or should I be setting up a middleware for routes?

D9705996's avatar

You could pass an array of roles to the directive then in you has role function

public function hasRole($names) {
  return collect($names)->intersect($this->roles)->count();
}

Then in the view

@role(['manager','admin'])

Tweak as needed ?

Please or to participate in this conversation.