Laravel Blade创建逗号分隔列表

时间:2018-05-23 10:38:05

标签: laravel laravel-blade

我有这个foreach:

@foreach ($ProdottoAccessori as $prodotto)
    @if($scheda->id == $prodotto->id)
        @foreach($prodotto['accessori'] as $acc)
           @foreach($acc['accessoriLang'] as $accNome)
                <span>{!! $accNome->accessori !!}</span>{{ $loop->last ? '' : ', ' }}
            @endforeach
        @endforeach
    @endif
@endforeach

会在每个项目之后添加逗号但不会在最后一个之后添加逗号。我认为代码是正确的,但它不起作用,我不知道为什么。

修改 这是$ProdottoAccessori

的控制器部分
$ProdottoAccessori = App\Product::has('accessori')->with([
    'productsLang',
      'accessori' => function ($query)  use ($array_prod_id){
          $query->with([
            'accessoriLang'
          ]);
       }
    ])->get();

3 个答案:

答案 0 :(得分:1)

您可以尝试laravel helper to array

collect($acc['accessoriLang'])->implode(',');

如果你已经有数组,那么你可以简单地使用。

$collection->implode(',')

有关详细信息,请查看https://laravel.com/docs/5.6/collections

@foreach ($ProdottoAccessori as $prodotto)
    @if($scheda->id == $prodotto->id)
        @foreach($prodotto['accessori'] as $acc)

                <span>{!! collect($prodotto['accessori'])->implode(',') !!}</span>
        @endforeach
    @endif
@endforeach

希望这有帮助

答案 1 :(得分:1)

好的 - 所以这就是我的想法:

在视图之外 - 无论是在控制器内还是在任何可以处理它的类中 - 然后将其注入视图,您可以执行以下操作:

$products = $ProdottoAccessori->map(function($product) {
    $product->accessori = $product->accessori->map(function($accessori) {
        $accessori->accessoriLangString = '<span>'.$accessori->accessoriLang->pluck('accessori')->implode('</span>, <span>').'</span>';
        return $accessori;
    });
    return $product;
});

现在在视图中你可以这样做:

@foreach ($products as $prodotto)
    @if($scheda->id == $prodotto->id)
        @foreach($prodotto->accessori as $acc)
            {{ $acc->accessoriLangString }}
        @endforeach
    @endif
@endforeach

或者你也可以这样做

@foreach ($products as $prodotto)
    @if($scheda->id == $prodotto->id)
        {{ $prodotto->accessori->pluck('accessoriLangString')->implode('') }}
    @endif
@endforeach

答案 2 :(得分:0)

这是解决方案。感谢@Sebastian Sulinski

在控制器中:

$ProdottoAccessori = App\Product::has('accessori')->with([
    'productsLang',
      'accessori' => function ($query)  use ($array_prod_id){
          $query->with([
            'accessoriLang'
          ]);
       }
    ])->get();

    $products = $ProdottoAccessori->map(function($product) {
        return $product->accessori->map(function($accessori) {
            $accessori->accessoriLangString = '<span>'.$accessori->accessoriLang->pluck('accessori')->implode(', ').'</span>';
            return $accessori;
        });
    });

在视图中:

@foreach ($ProdottoAccessori as $prodotto)
    @if($scheda->id == $prodotto->id)
        {{ $prodotto->accessori->pluck('accessoriLangString')->implode(', ') }}
    @endif
@endforeach

我仍然不知道为什么我要崩溃2次但它有效。

这是输出:

<span>cerchi in lega</span>, <span>alzacristalli</span>, <span>portapacchi</span>, <span>navigatore</span>