xxdalexx's avatar

Policy Authorize Redirect Instead of 403

Is there a way to accomplish this:

if (Gate::denies('edit', $masterlist)) {
    return redirect()->route('masterlist.index');
}

while using:

$this->authorize($masterList);
0 likes
7 replies
rsands's avatar
rsands
Best Answer
Level 2

You can do this in the Exceptions\Handler.php file

The render method overrides the classes AuthorizationException which is what authorize() will throw if a user is denied.

Inside the render method you could do

if($exception instanceof AuthorizationException) {
//your code
}
3 likes
afshin.asghari's avatar

I think in newer versions of Laravel (I'm using 5.6 now) mentioned solution won't work.

crnkovic's avatar

@afshin.asghari It does work, putting $exception instanceof AuthorizationException into the render method of a handler :)

1 like
afshin.asghari's avatar

@crnkovic I'm putting exactly

    if ($exception instanceof AuthorizationException){
        return redirect(route('profile.index'));
    }

above return parent::render($request, $exception); line

in the render method , but its not effective can you guide me through whats wrong?

update:

I removed the if condition and it works but of course it return all kinds of error to profile , maybe the Exception that Gate throws is not Authorization ?

crnkovic's avatar

Imported AuthorizationException? I tested ir on my machine on 5.6 and works just fine.

1 like

Please or to participate in this conversation.