Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
117 views
in Technique[技术] by (71.8m points)

php - Is it possible to use mutators on array? Laravel

I have a table like this:

@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

And for the name, I want to use a murator to strip out the name that is too long.

Here is:

public function getShortProdNameAttribute()
  {
      return substr($this->name, 0, 10);
  }

Now how can I use it?

$item['Short_Prod_Name'] doesn't work, this is the first time I try to use a mutator on an array. How can i do this?

P.S.In other questions, they wrote that it is better to use casts, but still, is the mutator applicable here?

question from:https://stackoverflow.com/questions/65865194/is-it-possible-to-use-mutators-on-array-laravel

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

According to the Laravel convention, the getShortProdNameAttribute() mutator will resolve to the short_prod_name attribute:

$item->short_prod_name

Rememeber to append the additional attribute in the Item class:

protected $appends = ['short_prod_name']

Thusly, the full code snippet is as follows:

@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

An alternative solution to address our problem is to use 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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...