Laravel 8 登录后如何在Blade/控制器中调用User关联的UserProfile数据
错误原因
Attempt to read property "image" on null 报错的核心是 Auth::user()->profile 为null,说明你创建用户时没有同步生成对应的UserProfile关联记录,登录后访问关联属性就触发了空对象读取异常。
修复方案
1. 保证用户创建时同步生成关联Profile
两种实现方式二选一即可:
方式A:通过模型事件自动创建(推荐)
在App\Models\User.php中添加boot逻辑,用户创建完成后自动生成关联的Profile记录,无需修改业务代码:
protected static function booted() { static::created(function ($user) { // 可根据业务需求填充Profile字段的默认值 $user->profile()->create([ 'image' => '/images/default-avatar.png', // 其他Profile必填字段在此处添加默认值 ]); }); }
方式B:在用户创建逻辑中手动生成
在你现有创建用户、登录的代码段中,新增创建Profile的逻辑:
// 原有创建用户的逻辑 $user = User::create($validatedUserData); // 新增:创建关联Profile $user->profile()->create([ 'image' => '/images/default-avatar.png', // 其他Profile必填字段在此赋值 ]); Auth::login($user, true); return $this->sendSuccessResponse();
2. 视图层做空值兜底兼容
哪怕已经加了自动创建逻辑,也建议在Blade模板中做空判断,避免极端场景下的异常:
<!-- 写法1:使用null合并运算符给默认值 --> <img src="{{Auth::user()->profile->image ?? '/images/default-avatar.png'}}" id="profile-img" alt=""> <!-- 写法2:Laravel 8+支持安全运算符,写法更简洁 --> <img src="{{Auth::user()->profile?->image ?? '/images/default-avatar.png'}}" id="profile-img" alt="">
3. 性能优化(可选)
如果多处需要用到登录用户的Profile数据,可以预加载关联避免N+1查询问题:
// 在控制器中获取登录用户时预加载关联 $user = Auth::user()->load('profile');
内容的提问来源于stack exchange,提问作者Mokhtar Ghaleb
相关产品推荐
相关产品推荐

