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

Laravel中全局访问当前登录用户,Auth::user()返回null如何解决?

问题根源

Auth::user()返回null的核心原因有两点:

  1. Laravel默认Auth配置指向的是User模型,你自定义的用户表对应模型是Person,Auth体系找不到对应查询的模型
  2. 注册逻辑中你仅手动写入了person_id到session,没有调用Auth的标准登录方法,Auth体系没有识别到登录状态

解决方案步骤

1. 调整Auth配置,指定用户模型

修改config/auth.php中的用户提供者配置,将默认的User模型替换为你的Person模型:

'providers' => [
    'users' => [
        'driver' => 'eloquent',
        'model' => App\Models\Person::class, // 替换为你Person模型的实际命名空间
    ],
],

同时确认你的Person模型继承了Illuminate\Foundation\Auth\User基类(不是默认的Model基类),并且指定了对应表名:

// Person模型中新增/修正以下配置
protected $table = 'people';
protected $fillable = ['email', 'password']; // 补充其他允许批量赋值的字段

2. 修正注册逻辑,调用标准Auth登录方法

你现在注册逻辑中手动存person_id到session的操作可以替换为Laravel自带的登录方法,Auth会自动处理会话存储,之后就能直接通过Auth::user()获取用户实例:

// 原signUp方法中$person->save()之后,替换原有session存储逻辑
if (!$person->save()) {
    return back()->with('status', 'Failed to save the person to the database');
}
// 删掉原有的$request->session()->put('person_id', $person->id); 替换为下面的代码
Auth::login($person, true); // 第二个参数传true相当于开启记住我,不需要的话传false

修改后你的登录逻辑无需调整,Auth::attempt成功后就会自动初始化登录状态,Auth::user()可以正常返回Person实例。

3. 全局配置控制器用户属性,避免重复查询

Laravel的Auth门面本身自带请求级缓存,同一次请求中多次调用Auth::user()只会执行一次数据库查询,你可以直接在基础控制器中注入用户实例,实现所有继承的控制器都可以通过$this->user访问:

// 你的BaseController.php中添加以下代码
protected $user;

public function __construct()
{
    $this->middleware(function ($request, $next) {
        $this->user = Auth::user();
        // 可选:将用户实例全局共享给所有视图,不需要的话可以删掉
        view()->share('current_user', $this->user);
        return $next($request);
    });
}

如果需要完全避免每次请求都查询数据库,可以将用户信息序列化存入session,修改登录逻辑:

// 登录/注册成功后将用户信息存入session
session()->put('cached_user', $person->toArray());

然后在中间件中优先从session读取用户信息:

$this->middleware(function ($request, $next) {
    if (session()->has('cached_user')) {
        $this->user = new Person(session()->get('cached_user'));
    } else {
        $this->user = Auth::user();
        session()->put('cached_user', $this->user?->toArray());
    }
    return $next($request);
});

注意:如果采用session缓存用户信息的方案,用户信息更新时需要同步更新session中的缓存数据,避免拿到过时的信息。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.28 03:54:02