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 :)
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...
}
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? )?