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

Laravel自定义登录注册后配置Auth中间件重定向至自定义登录页

解决Laravel自定义Auth登录页的重定向问题

嘿,这个问题其实很好搞定,Laravel的Auth中间件本身就预留了自定义重定向的空间,你只需要修改默认的Authenticate中间件就行,给你两种靠谱的实现方式:

方法一:重写redirectTo方法(推荐)

这是最符合Laravel规范的做法,灵活性也更高,适合后续扩展。

  1. 打开项目里的 app/Http/Middleware/Authenticate.php 文件
  2. 找到并替换原有的redirectTo相关代码,改成下面这样:
<?php

namespace App\Http\Middleware;

use Illuminate\Auth\Middleware\Authenticate as Middleware;

class Authenticate extends Middleware
{
    /**
     * Get the path the user should be redirected to when they are not authenticated.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return string|null
     */
    protected function redirectTo($request)
    {
        if (! $request->expectsJson()) {
            // 这里直接使用你的自定义登录路由名称
            return route('login.create');
        }
    }
}

这样修改后,所有应用了Auth中间件的路由,只要用户未认证,就会自动跳转到你定义的login.create路由对应的登录页面。

方法二:使用闭包设置redirectTo属性

如果你不需要额外的逻辑,也可以直接给redirectTo属性赋值一个闭包,同样能达到效果:

同样打开app/Http/Middleware/Authenticate.php,修改成:

<?php

namespace App\Http\Middleware;

use Illuminate\Auth\Middleware\Authenticate as Middleware;

class Authenticate extends Middleware
{
    /**
     * The path the user should be redirected to when they are not authenticated.
     *
     * @var string|\Closure
     */
    protected $redirectTo = function () {
        return route('login.create');
    };
}

两种方法都能实现你的需求,个人更推荐第一种,因为后续如果需要根据请求类型、用户角色等做不同的重定向,直接在redirectTo方法里加逻辑就行。

内容的提问来源于stack exchange,提问作者King Rayhan

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.15 07:32:32