Laravel JsonResource关联字段为空:编辑页读取title属性报错
问题分析与解决
核心问题
编辑页抛出“Attempt to read property "title" on null”错误,本质是$this->typeEducation为null时直接访问->title导致的。列表页能正常显示,说明列表内的Education记录都存在对应的EducationType关联,但编辑页操作的这条记录要么education_type_id字段为空,要么对应的EducationType已被删除,或是关联加载逻辑出现异常。
具体修复步骤
1. 安全访问关联字段(优先处理)
在EducationResource中对关联字段做null安全处理,避免直接调用属性触发报错:
// 替换原有type字段的定义 'type' => $this->typeEducation?->title, // PHP 8+ 语法 // 兼容PHP 7的写法: // 'type' => optional($this->typeEducation)->title,
2. 预加载关联,优化性能与稳定性
在控制器index方法中预加载typeEducation关联,既避免N+1查询问题,也能确保关联数据的稳定性:
public function index(): Response { return Inertia::render('School/Education/EducationIndex', [ 'education' => EducationResource::collection(Education::with('typeEducation')->get()) ]); }
3. 清理资源中无效的关联字段
EducationResource内的educationTypes字段引用了模型中不存在的educationTypes关联(模型仅定义了typeEducation单数关联),且控制器已单独传递educationTypes数据,直接删除该字段即可:
// 移除以下无效代码行 // 'educationTypes' => EducationTypeResource::collection($this->whenLoaded('educationTypes'))
4. 验证数据完整性
检查编辑页对应的Education记录:
- 确认
education_type_id字段不为空 - 确认该
education_type_id存在对应的EducationType记录
内容的提问来源于stack exchange,提问作者ontwikkelaar15
相关产品推荐
相关产品推荐

