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

Laravel默认auth中间件始终跳转登录页(已认证仍跳转)求助

Laravel Auth中间件跳转异常问题

问题详情

  • 按Laravel文档手动实现登录控制器,通过dd(Auth::user())已确认用户成功登录
  • 为路由添加auth中间件后,访问时始终被强制跳转至登录页面
  • 用户表已将默认主键字段id修改为nim

解决方案

1. 配置User模型主键

在app/Models/User.php中明确指定主键字段,并根据nim的类型调整相关设置:

// 指定主键为nim
protected $primaryKey = 'nim';

// 如果nim是字符串类型(非自增整数),添加以下两行
public $incrementing = false;
protected $keyType = 'string';

2. 确认认证配置正确性

检查config/auth.php中的用户认证提供者配置,确保指向正确的User模型:

'providers' => [
    'users' => [
        'driver' => 'eloquent',
        'model' => App\Models\User::class,
    ],
],

3. 修正登录逻辑的认证字段

如果自定义了登录控制器,确保attempt方法使用nim作为用户标识字段:

public function login(Request $request)
{
    $credentials = $request->validate([
        'nim' => 'required',
        'password' => 'required'
    ]);

    if (Auth::attempt($credentials)) {
        $request->session()->regenerate();
        return redirect()->intended('/dashboard');
    }

    return back()->withErrors([
        'nim' => '账号或密码错误',
    ]);
}

4. 清除缓存与Session

执行以下命令清除配置缓存和Session,确保新配置生效:

php artisan config:clear
php artisan cache:clear
php artisan session:clear

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.25 20:12:14