首页 > 解决方案 > 将保存在数据库中的数组格式化为 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);
}

我希望购物车显示如下。

标签: arrayslaravel

解决方案


在模型中使用 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


推荐阅读