首页 > 解决方案 > 是否可以在数组上使用变异器?拉拉维尔

问题描述

我有一张这样的桌子:

@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 是否适用于这里?

标签: phplaravel

解决方案


根据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

推荐阅读