arrays - 将保存在数据库中的数组格式化为 laravel 中的刀片视图
问题描述
我有一个存储 id、cart(array)、updated_at、created_at 的数据库表。如何解构数组并将视图中的项目显示为列表项。
3
{"3":{"name":"iPhone","quantity":2,"price":"500.00"},"4": {"name":"Samsung","quantity":1,"price ":"344.00"}}
2019-11-10 07:50:53
______________________
ProductsController
______________________
public function cartsIndex(Request $request)
{
$carts = Cart::all();
$carts = json_decode($carts);
// return view('cartsIndex')->with(['carts' => $carts]);
dd($carts);
}
我希望购物车显示如下。
编号 - 3
名称:苹果手机
- 数量:2
- 价格:500
名称:三星
- 数量:1
- 价格:344
解决方案
在模型中使用 laravel 的 $cast 属性。它会自动帮助您在存储在数据库中时将数据转换为 json,并在您检索它们时帮助您将它们作为数组访问。
protected $cast = [
'cart' => 'array' // name of the column you want to store as json and retrieve as array
];
供参考https://laravel.com/docs/6.x/eloquent-mutators#array-and-json-casting
推荐阅读
- azure-active-directory - Microsoft Graph 上的 LDAP 不明确名称解析 (ANR) 等效项
- powershell - 如何剪切字符串中的特定字符并将其保存到新文件中?
- python - Django - InheritanceManager 不工作
- android - 如何启动第一个线程完成到第二个线程启动后
- python - pydrive:为什么突然出现这个验证错误?
- javascript - Dropzone多个文件上传不适用于Excel文件
- jsf - 表单未在具有片段“渲染”条件和 ui:param 的页面上提交
- powershell - 排除 Powershell 密码生成器中的特定单词
- android - 期望适配器在恢复状态时是“新鲜的”
- android - 在 Android 中使用改造解析嵌套的 json