How to Redirect Unauthorized Users | This action is unauthorized Laravel Policy
The problem in Laravel is it doesn’t redirect unauthorized users to a specific page but just throw an exception to the user, to redirect to 403 custom forbidden page you have to edit the laravel by default code.
Possible Solution 1 – Redirect Unauthorized Users Laravel
Please navigate to the App\Exceptions\Handler.php and open the Handler.php file.
And use Authentication Exception Class at the top.
1 |
use Illuminate\Auth\Access\AuthorizationException; |
Now scroll down to the public function render($request, Exception $exception) function
1 2 3 4 5 6 7 8 9 10 11 12 13 |
public function render($request, Exception $exception) { if ($exception instanceof AuthorizationException) { if ($request->expectsJson()) { return response()->json(['error' => 'Unauthorized.'], 403); } // TODO: Redirect to error page instead // Redirect user from here whatever the route you want. return redirect()->route('error'); } // this will still show the error if there is any in your code. return parent::render($request, $exception); } |
Final Words – This Action is Unauthorized Laravel
That’s it. You don’t need to do anything else. Redirect the user from the route using middleware. If you still have a question please ask in the comment we will try our best to keep in touch with you.