如何重写Laravel未认证用户的跳转路由?
重写Laravel的unauthenticated方法以替换默认跳转路由
你只需要在项目的app/Exceptions/Handler.php文件中重写unauthenticated方法即可,具体操作:
- 首先在文件顶部引入
AuthenticationException类:
use Illuminate\Auth\AuthenticationException;
- 然后在Handler类中添加(或覆盖)
unauthenticated方法,将默认的route('login')替换为route('home'):
/** * Handle authentication exceptions. * * @param \Illuminate\Http\Request $request * @param \Illuminate\Auth\AuthenticationException $exception * @return \Illuminate\Http\Response */ protected function unauthenticated($request, AuthenticationException $exception) { return $this->shouldReturnJson($request, $exception) ? response()->json(['message' => $exception->getMessage()], 401) : redirect()->guest($exception->redirectTo() ?? route('home')); }
修改完成后,所有触发框架默认unauthenticated方法的场景,都会跳转到你指定的home路由,和自定义的Authenticate中间件逻辑保持一致,不会再因找不到login路由报错。
内容的提问来源于stack exchange,提问作者realtebo
相关产品推荐
相关产品推荐

