Anirudh
Anirudh

Reputation: 3418

How to remove comma in last item of foreachloop in laravel?

I tried adding last item logic using if condition, but the code is getting displayed.

My existing code :

<script type='application/ld+json'> 
{
  "itemListElement":
[
  @foreach($product->Offers as $offer)
   {
    "@type": "Offer",
    "name": "{{$offer->title}}",
    "price": "{{$offer->displayPrice}}",
   },  
   @endforeach 
 ]
}

}
</script>

Upvotes: 0

Views: 1071

Answers (2)

Komal
Komal

Reputation: 2736

Try to do this

<?php $i = 1; $len = count($product->Offers); ?>
@foreach($product->Offers as $offer)
  {
  "@type": "Offer",
  "name": "{{$offer->title}}",
  "price": "{{$offer->displayPrice}}",
  }<?php if($i < $len){echo ',';} $i++;?>
@endforeach

Upvotes: 1

Alexey Mezenin
Alexey Mezenin

Reputation: 163968

Try to use $loop->last():

@foreach($product->Offers as $offer)
{
    "@type": "Offer",
    "name": "{{$offer->title}}",
    "price": "{{$offer->displayPrice}}",
}{{ $loop->last() ? '' : ',' }}
@endforeach 

Upvotes: 4

Related Questions