Closed abodnar closed 1 year ago
The problem lies in this piece of code:
$clientViewAbility = Bouncer::ability()->firstOrCreate([
'name' => 'client_view',
'title' => 'View Clients',
]);
This ability is not connected to any model. To create a model ability, you must set the entity_type
:
$clientViewAbility = Bouncer::ability()->firstOrCreate([
'name' => 'view', // You can use 'client_view', though I wouldn't recommend it
'title' => 'View Clients',
'entity_type' => Client::class,
]);
Then assign it using:
Bouncer::allow($viewerRole)->to($clientViewAbility);
What you were doing was mixing two separate things. The to
method takes either an actual ability model or a name and entity. Not both.
So you can do either:
Bouncer::allow($viewerRole)->to($abilityModel);
or
Bouncer::allow($viewerRole)->to('view', Client::class);
...in which case Bouncer will automatically find/create the ability for you.
If you look at the to
method:
...and follow it down to the getAbilityIds
method:
...you'll see that if the first argument is an actual ability, the rest of the arguments are ignored.
🤦 I can't believe how simple that was. That totally solved it for me and make sense.
Thanks for working through this with me.
Per our conversation on Mastodon, I'm running into the situation where despite a user having the role that has the ability to view clients, I'm receiving a 403.
Setup:
User class:
Client class:
Route:
Controller:
I tried two other situations.
I changed the
$this->authorize('client_view');
and that did work for my user, but if I try$this->authorize('client_view', $client);
it fails for the Admin user.