
在 Laravel Blade 模板中,当数据库字段存储的是 JSON 格式字符串(如 non_sql 字段),需先解码为 PHP 数组或对象,再遍历提取键值对;直接使用 json_decode() 返回对象会导致 Blade 渲染报错,应结合 json_decode($json, true) 转为关联数组,并用 @foreach 或 implode() 安全输出。
在 laravel blade 模板中,当数据库字段存储的是 json 格式字符串(如 `non_sql` 字段),需先解码为 php 数组或对象,再遍历提取键值对;直接使用 `json_decode()` 返回对象会导致 blade 渲染报错,应结合 `json_decode($json, true)` 转为关联数组,并用 `@foreach` 或 `implode()` 安全输出。
Blade 模板中无法直接渲染 stdClass 对象(json_decode() 默认返回对象),因此以下写法会报错:
{{ json_decode($item["non_sql"]) ?? 'NA' }}
// ❌ 错误:htmlspecialchars() expects string, stdClass given
✅ 正确做法是:强制转为关联数组,再结构化输出。推荐两种清晰、可维护的方式:
方式一:使用 @foreach 逐项渲染(推荐,语义清晰、易定制)
<td>
@php
$data = json_decode($item['non_sql'], true);
$inner = $data['data'] ?? [];
@endphp
@forelse($inner as $key => $value)
{{ $key }}: {{ $value }}<br>
@empty
NA
@endforelse
</td>
方式二:使用 implode() 快速拼接(适合简单展示)
<td>
@php
$data = json_decode($item['non_sql'], true);
$pairs = [];
foreach ($data['data'] ?? [] as $k => $v) {
$pairs[] = "$k: $v";
}
echo implode('<br>', $pairs) ?: 'NA';
@endphp
</td>
⚠️ 注意事项:
详细的 Three.js 3D 图形参考,涵盖场景设置、相机、几何体、材质、光照、动画、控制器、加载器、数学工具和调试。
- 始终传入
true作为json_decode()的第二个参数,确保返回关联数组而非对象; - 必须做空值/键存在性检查(如
?? []和['data'] ?? []),避免Undefined index错误; - Blade 中
{{ }}会自动转义 HTML,若需保留<br>等标签,请改用{!! !!}(但需确保内容可信,防止 XSS); - 更佳实践:将 JSON 解析逻辑移至 Eloquent 访问器(Accessor)中,提升模板可读性与复用性:
// 在模型中定义访问器
public function getNonSqlDataAttribute()
{
$json = $this->attributes['non_sql'] ?? '';
$decoded = json_decode($json, true);
return $decoded['data'] ?? [];
}
然后 Blade 中可直接使用:
<td>
@forelse($item->non_sql_data as $key => $value)
{{ $key }}: {{ $value }}<br>
@empty
NA
@endforelse
</td>
这样既保障安全性,又让视图层保持简洁、健壮、易于测试。










