Laravel Blade中解析JSON字段输出时报获取非对象属性'en'错误
报错原因
你遇到的Trying to get property 'en' of non object错误,本质是json_decode($program->title)执行后没有返回标准对象,你对非对象值访问en属性就会触发这个报错,常见诱因有三类:
- 数据表中部分
program记录的title字段为空(null、空字符串),或者存储的内容不是合法JSON格式,导致解码失败返回null - 部分记录的title字段JSON结构缺失
en/ar字段 - 没有在模型层做JSON字段自动转换,每次在模板手动解码缺少容错逻辑
修复方案
优先从模型层做标准化处理,这是Laravel项目处理JSON字段的推荐实践,一劳永逸:
- 打开对应Program模型,在
$casts配置中添加title字段的JSON类型转换,框架会自动完成数据库JSON格式和PHP数组的双向转换,不需要每次手动调用json_decode:
// 对应模型文件内 protected $casts = [ 'title' => 'array', 'is_shown' => 'boolean', ];
- 调整Blade模板的输出逻辑,加入兜底容错,避免字段缺失、空值触发报错:
<tr> <th>Title en</th> <th>Title ar</th> <th>Description</th> <th>Session Number</th> <th>Session Per Week</th> <th>Session Duration</th> <th>Show</th> </tr> @foreach($model as $program) <tr> <th>{{ data_get($program->title, 'en', '') }}</th> <th>{{ data_get($program->title, 'ar', '') }}</th> <th>{{ $program->description }}</th> <th>{{ $program->sessions_number }}</th> <th>{{ $program->sessions_per_week }}</th> <th>{{ $program->session_duration }}</th> <th>{{ $program->is_shown ? 'Yes' : 'No' }}</th> </tr> @endforeach </thead>
这里用Laravel内置的data_get()辅助函数做容错,不管title是null、还是对应语言键不存在,都会输出你指定的默认空字符串,不会中断页面渲染。
如果你暂时不想调整模型配置,也可以在模板内临时解码加空合并运算符兜底,不过这种写法冗余度高,不建议长期使用:
@php($decodedTitle = json_decode($program->title, true)) <th>{{ $decodedTitle['en'] ?? '' }}</th> <th>{{ $decodedTitle['ar'] ?? '' }}</th>
排查提示:可以先执行查询统计下title字段为空、格式非法的脏数据数量,从数据源层面修正不符合格式的记录,能从根源避免这类问题。
内容的提问来源于stack exchange,提问作者ibrahim khalaf
相关产品推荐
相关产品推荐

