Laravel:如何在我的视图中使用 json_decode?

Laravel: How can I use json_decode in my view?

我正在尝试找出从我的 blade 模板中的序列化数组获取属性的最佳方法。

MyController.php

$cart = Cart::findOrFail($id);
...
return view('view', ['cart' => $cart]);

所以在这种情况下 $cart 中有许多项目 (objects) 正在传递给视图。

cart.blade.php

...

@each('show', $cart->items()->get(), 'item')

...

在此视图中,我可以通过以下方式访问内容:

show.blade.php

<p>$item->name</p>
<p>$item->color</p>
...

但是 $item 也有一个序列化属性,其中包含诸如 sku、重量、数量等内容。

// $item->serialized_item = {"id":123,"quantity":5,"...} (string)

所以在我的 show.blade.php 视图中,我需要做如下事情:

json_decode($item->serialized_item)

现在我只是导入另一个视图来帮助保持整洁,但我认为这不是最好的方法。

cart.blade.php

...
@include('detail', ['attributes' => item->serialized_item])

detail.blade.php

<?php
    $foo = json_decode($item->serialized_item, true);
?>

<p>{{$foo['quantity']}}</p>  // 5

此方法有效,但似乎是个 hack。

您需要更改 item 模型以创建 setSubAttributes() 方法:

public function setAttributes() {
    $attributes = json_decode($this->serialized_item, true);

    $this->id = $attributes ['id'];
    $this->quantity = $attributes ['quantity'];
}

并在您的控制器中调用它来准备视图的日期:

$cart = Cart::findOrFail($id);
$items = $cart->items()->get();

foreach ($items as &$item) {
  $item->setAttributes();
}

以便您现在可以直接在 detail.blade.php 视图中调用您的属性。

编辑

我没试过,但你甚至可以直接在你的 item 模型构造函数中调用它,这样你就可以避免在控制器中调用它:

public function __construct()
{
    $this->setAttributes();
}