Home > Mobile >  Laravel foreach loop adds start and end whitespaces
Laravel foreach loop adds start and end whitespaces

Time:01-03

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?

CodePudding user response:

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 a better fix is to use some of Laravel's collection methods to avoid the problem completely:

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

CodePudding user response:

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

@isset($team->players)
    {{ '('. implode(', ', $team->players). ')' }}
@endisset
  • Related