1

I have this simple loop in a Laravel blade

@foreach ($team->players as $player)
 {{$loop->first ? "(" : ""}}
 {{!$loop->first ? ", " : ""}} {{$player->name}}
 {{$loop->last ? ")" : ""}}
@endforeach

but I end up with whitespaces after the opening and before the closing braces. Like this

( Player One, Player 2 )

How can I stop this?

Dan E
  • 167
  • 1
  • 11

2 Answers2

6

You're getting spaces bcs only the stuff between {{ }} gets processed by PHP in Blade templates. The rest shows up in your HTML exactly as typed - so spaces used for formatting your code, indenting, etc, all show up in your HTML. And if those spaces are in the middle of text, you'll see them rendered in the browser.

    @foreach ($team->players as $player)
     {{$loop->first ? "(" : ""}}
//  ^-- space here, if you had text before the opening bracket you'll see it
    {{!$loop->first ? ", " : ""}} {{$player->name}}
//  -----------------------------^ space here, even for first name 
     {{$loop->last ? ")" : ""}}
//  ^-- space here, shows up after last name 
    @endforeach

If you want to stick with the loop you can, by getting rid of the spaces, but it is messy and not very readable:

@foreach ($team->players as $player)
    {{ $loop->first ? "(" : "" }}{{! $loop->first ? ", " : ""}}{{$player->name}}{{ $loop->last ? ")" : "" }}
@endforeach

But using a loop is really only necessary if you need to actually handle or manipulate the values one-by one before displaying. If you don't, there's a standard, simple solution to join up an array of values in PHP, using implode(). In your case you first need to generate the array of names from your Collection to pass to implode(). Maybe something like:

({{ implode(', ', array_column($team->players->toArray(), 'name')) }})

But this is also a bit clumsy and overly complicated. You're using Laravel, and your data is a Collection, so it makes sense to investigate the Collection methods available. Sure enough, there's an implode() method which makes evertyhing much simpler:

({{ $team->players->implode('name', ', ') }})
Don't Panic
  • 13,965
  • 5
  • 32
  • 51
2

Let me show you a better way: Remove foreach and use implode.

@isset($team->players)
    {{ '('. implode(', ', $team->players). ')' }}
@endisset
matiaslauriti
  • 7,065
  • 4
  • 31
  • 43