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

thewoodcutter's avatar

How do I use roles and permissions in controllers?

Hello again. I think I've got a handle on the front end using blade with the (I'm using backpack permissions) Laravel Permissions, such as using the @can and @if(auth()->user()->hasRole('Admin')) but I'm now trying to understand how to gate my controllers using roles. The logic required I haven't found online or can figure out as I'm rather new to PHP. Any links/explains would help, thanks :)

0 likes
2 replies
bencarter78@hotmail.com's avatar

You would want to do something like this I think...

// AuthServiceProvider
public function boot()
{
    ...

    Gate::define('update-post', function ($user, $post) {
        return $user->hasRole('Admin');
    });
}

// Then in your controller...
if (Gate::allows('update-post', $post)) {
    // The current user can update the post...
}

This was basically taken from the docs here https://laravel.com/docs/5.6/authorization

thewoodcutter's avatar

Ahh okay, so use Gates. I just finished getting routeMiddleware to work with backpack/permissionsmanager by copying three files from the latest version of spatie/laravel-permissions source.. I now can 'gate' my routes with it.

I actually understand the use of Gate you're mentioning, though I haven't looked at Gates just yet. Is your example using the spatie package ( hasRole() is a specific from that? )?

Thanks @bencarter78

Please or to participate in this conversation.