Laravel display <p> tag content with a if condition

I’m working on a laravel project. I display content in a html (p) tag by passing it through a foreach block and I want to separate all the iterations with a comma. So here is how I do it:

<p class="text-2xl">
   @foreach ($user->rateSchedule as $schedule)
      {{ $schedule->disciplines->name }}
      @if (!$loop->last)
         {{ ',' }}
      @endif
   @endforeach
</p>

Suppose to display like that:
Acupuncture, Reiki, Acupuncture

But when the comma is displayed there is a space before it.

It’s displayed like this :
Acupuncture , Reiki , Acupuncture

I would like to remove the space before the comma. But i dont know how to do it.

>Solution :

The unwanted space you’re seeing before the comma is due to the way blade templating engine in Laravel processes content inside {{ ... }} blocks. It automatically adds a space before and after the content.

To remove the space before the comma, simply write the logic without spaces or newlines:

<p class="text-2xl">
   @foreach ($user->rateSchedule as $schedule)
      {{ $schedule->disciplines->name }}@if(!$loop->last),@endif
   @endforeach
</p>

This should display your desired output as: Acupuncture, Reiki, Acupuncture.

This approach makes sure there’s no extra space before the comma.

Leave a Reply