php - 是否可以在数组上使用变异器?拉拉维尔
问题描述
我有一张这样的桌子:
@foreach($order->cart->items as $item)
<tr>
<th scope="row"><a href="/{{ $item['code_cat'] }}/{{ $item['url_cat'] }}/{{ $item['prod_url'] }}"><img class="basketimg mr-1" src="/img/products/{{$item['img']}}"><span class="basket-prod-name">{{ $item->Short_Prod_Name() }}</span></a></th>
<td class="text-center">
<div class="prodcount">{{$item['qty']}}</div>
</td>
<td class="text-right">{{$item['cost']}}AZN</td>
</tr>
@endforeach
对于名字,我想用一个 murator 去掉太长的名字。
这是:
public function getShortProdNameAttribute()
{
return substr($this->name, 0, 10);
}
现在我该如何使用它?
$item['Short_Prod_Name']
不起作用,这是我第一次尝试在数组上使用增变器。我怎样才能做到这一点?
PS在其他问题中,他们写道最好使用casts
,但是,mutator 是否适用于这里?
解决方案
根据Laravel
约定,getShortProdNameAttribute()
mutator 将解析为short_prod_name
属性:
$item->short_prod_name
请记住在Item
类中附加附加属性:
protected $appends = ['short_prod_name']
因此,完整的代码片段如下:
@foreach($order->cart->items as $item)
<tr>
<th scope="row"><a href="/{{ $item['code_cat'] }}/{{ $item['url_cat'] }}/{{ $item['prod_url'] }}"><img class="basketimg mr-1" src="/img/products/{{$item['img']}}"><span class="basket-prod-name">{{ $item->short_prod_name }}</span></a></th>
<td class="text-center">
<div class="prodcount">{{$item['qty']}}</div>
</td>
<td class="text-right">{{$item['cost']}}AZN</td>
</tr>
@endforeach
解决我们问题的另一种解决方案是使用 Str::limit
:
@foreach($order->cart->items as $item)
<tr>
<th scope="row"><a href="/{{ $item['code_cat'] }}/{{ $item['url_cat'] }}/{{ $item['prod_url'] }}"><img class="basketimg mr-1" src="/img/products/{{$item['img']}}"><span class="basket-prod-name">{{ Str::limit($item->name, 10) }}</span></a></th>
<td class="text-center">
<div class="prodcount">{{$item['qty']}}</div>
</td>
<td class="text-right">{{$item['cost']}}AZN</td>
</tr>
@endforeach
推荐阅读
- r - mongolite:如何执行 LIKE 查询?
- html - 如何使用 *ngFor 显示数据
- javascript - 使用 ajax 时提交的“未定义”数据
- android - 如何以编程方式获取 Android 程序的信息或 nfc id?
- sql - 使用 SQL 查询计算每日频率的累积计数(在 Amazon Redshift 中)
- r - 如何将底图添加到 R 中的 tmap 图?
- eclipse - 如何隐藏 RCP 中的默认上下文菜单项?
- typescript - 如何防止 typescript tsc 编译 ../node_modules?
- dynamic - PowerBI · 要测量的表的点击值
- dictionary - 获取字典的值
从隐藏字段到asp.net mvc中的post方法