【发布时间】:2016-06-17 23:41:30
【问题描述】:
我正在尝试找出从刀片模板中的序列化数组中获取属性的最佳方法。
MyController.php
$cart = Cart::findOrFail($id);
...
return view('view', ['cart' => $cart]);
所以在这种情况下,$cart 中有许多项目(对象)正在传递给视图。
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。
【问题讨论】: