You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何重写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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.06 00:24:58