Jop
Jop

Reputation: 13

How to pass multiple params to policy through Laravel route middleware

I am trying to pass multiple arguments to my policy method. I am calling the policy as a middleware on my route. In my policy I need the authenticated user, the target group and the invitee. The authenticated user gets passed automatically by Laravel.

I wish to call the policy like this so it matches my other routes, but this always returns a 403 forbidden. I believe this happens because the middleware doesn't know which policy to use.

Route::post('/{group}/invite/{invitee}', [GroupInvitationController::class, 'store'])
    ->middleware('can:store,group,invitee');

If I use this line in my controller method instead of calling it from the route using middleware it works perfectly.

$this->authorize('store', [GroupInvitation::class, $group, $invitee]);

My policy:

class GroupInvitationPolicy
{
    public function store(User $user, Group $group, User $invitee) {
        return $user->isGroupAdminOf($group) || (
            $group->users->contains($invitee)
                ? Response::allow()
                : Response::deny('User is already part of group')
        );
    }
}

Is there a way to call the policy from the route middleware while also providing the policy with the correct parameters?

Upvotes: 1

Views: 1350

Answers (0)

Related Questions