skip to Main Content

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.

2

Answers


  1. Instead of looping over the schedules and printing them out one by one, you can do something like this:

    <p class="text-2xl">
        {{ Arr::join(Arr::map($user->rateSchedule, fn($schedule) => $schedule->disciplines->name), ', ') }}
    </p>
    

    This works by first mapping each schedule to the discipline’s name using Arr::map(), then joining each name together with commas using Arr::join().

    The extra spaces in your initial solution is likely due to the indentation/line breaks in each line. Blade does not differentiate between indentation/line breaks and intended whitespace.

    Login or Signup to reply.
  2. You can try this:

    <p class="text-2xl">{{ $user->rateSchedule->pluck('disciplines.name')->implode(',') }}</p>
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search