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

Laravel使用auth()->user()->id获取用户ID报null属性读取错误如何解决

错误根因

这个错误出现的核心原因是当前请求触发控制器方法时,用户未经过身份认证,auth()->user()返回了null,此时尝试读取null的id属性就会抛出对应错误。

修复方案
  • 优先给对应路由添加auth中间件,从入口层面限制只有已登录用户才能访问该接口,路由定义示例:
Route::post('/appointment/check', [YourController::class, 'check'])->middleware('auth');
  • 在控制器方法开头增加登录状态校验兜底,避免未登录用户进入后续业务逻辑,同时可以用Laravel自带的auth()->id()方法简化用户ID获取逻辑,优化后代码如下:
public function check(Request $request) {
    // 新增登录校验
    if (!auth()->check()) {
        return redirect()
            ->to('/login')
            ->with('errmessage', '请先登录后再操作');
    }

    $date = $request->date;
    $appointment = Appointment::where('date', $date)
        ->where('user_id', auth()->id())
        ->first();

    if (!$appointment) {
        return redirect()
            ->to('/appointment')
            ->with('errmessage', '该日期暂无可预约时段');
    }

    $appointmentId = $appointment->id;
    $times = Time::where('appointment_id', $appointmentId)->get();

    return view('admin.appointment.index', compact('times', 'appointmentId', 'date'));
}
  • 额外说明:auth()->id()是Laravel提供的快捷方法,会直接返回已认证用户的ID,未登录时返回null,无需先获取用户实例再读取属性,写法更简洁。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.10 20:03:03