$this->authorize() does not work in controller

Published 4 months ago by sork

I have created OfferPolicy class to provide authorization to resource action in Offer model. i have followed below steps:

create OfferPolicy.

php artisan make:policy OfferPolicy --model=Offer

register OfferPolicy in AuthServiceProvider

protected $policies = [
        Offer::class => OfferPolicy::class        
    ];

update policy in OfferPolicy class


public function update(User $user, Offer $offer)
    {
        return $user->id == $offer->user_id;
    }

OfferController


public function update(Request $request, Offer $offer)
    {
        $this->authorize('update', $offer);
        
        $offer->update($request->all());

    return redirect()->route('offers.index')
}

when I am trying to update an offer, below error is coming.

Symfony \ Component \ HttpKernel \ Exception \ AccessDeniedHttpException
This action is unauthorized.

Anyone can help me on this problem, did i forget anything?

Best Answer (As Selected By sork)
sork

@36864 thanks for your support. just found the mistake, i forgot to call Offer model in AuthServiceProvider.

36864
36864
4 months ago (61,750 XP)

Dump the user and offer objects in your policy method to make sure you're getting the data you expect in there and paste the results here.

public function update(User $user, Offer $offer)
{
    dd($user, $offer);
    return $user->id == $offer->user_id;
}
sork

@36864 already did it, same message (This action is unauthorized.) comes.

36864
36864
4 months ago (61,750 XP)

Did you define a before method in your policy? If so, make sure it's not returning false.

sork

@36864 thanks for your support. just found the mistake, i forgot to call Offer model in AuthServiceProvider.

Please sign in or create an account to participate in this conversation.