I can't find it on the documentation. How to redirect unauthorized user?
RolePolicy.php
class RolePolicy
{
use HandlesAuthorization;
public function manageRoles(User $user)
{
return $user->isAdmin();
}
}
RolesController.php
function __construct()
{
$this->authorize('manageRoles', Role::class);
}
Thanks in advance
You can modify file app\Exceptions\Handler.php
on the render function:
public function render($request, Exception $e)
{
/**modified part**/
if ($request->wantsJson()) {
return response([
'success' => false,
'message' => $e->getMessage()
], 404);
}
if ($e instanceof AuthorizationException) {
return redirect('path');
//or simply
return view('errors.forbidden');
//but this will return an OK, 200 response.
}
/**end of modified part**/
return parent::render($request, $e);
}
If you want to put a 403, use helper function response().
You can see the documentation for responses here https://laravel.com/docs/master/responses
Basically you can use the solution to play with more options. But the easiest way is just to create a view file:
errors/403.blade.phpand that view will automatically load when you hit unauthorized exceptions. The same will work for 404 not found, just create the404.blade.php.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With