mi-ho
mi-ho

Reputation: 167

Laravel add commas between array elements

I have this "tags" array and I want to add commas in between the links in my article.blade.php. Originally, this is the tags code:

<b>Tags:</b> 
@foreach($article->tags as $tag)
    <a href="/tag/'{{ $tag->name }}">{{ $tag->name }}</a>
@endforeach

I want this result

Tags: tag1, tag2, tag3

How do I do this so it looks right in an elegant way?

PS Meanwhile I found the solution. Here it is:

[SOLUTION]

The tags must be pre-defined in the controller(ArticlesController.php) here:

public function show(Article $article){     
    foreach($article->tags as $tag){
        $tags[]= link_to('tag/'.$tag->name, $tag->name, $tag->name);
    }   
    return view('page.article',compact('article','tags'));
}

Next you can leave your articles.blade.php like this:

<b>Tags:</b> 
{!! implode(', ',$tags) !!}

Let me know if you can think of something better.

Upvotes: 0

Views: 3195

Answers (3)

GerryB
GerryB

Reputation: 31

@foreach($article->tags as $tag)

    {{ $tag }}
    @if (!$loop->last),@endif

@endforeach

Upvotes: 3

Ricardo Carvalho
Ricardo Carvalho

Reputation: 413

in article.blade.php:

@foreach($article->tags as $tag)
    <a href="/tag/'{{ $tag->name }}">{{ $tag->name }}</a>
    @if($loop->last)
        .
    @elseif($loop->remaining == 1)
        &nbsp;&amp;&nbsp;
    @elseif(!$loop->first)
        ,&nbsp;
    @endif
@endforeach

will include "&" and "." and output: Tag1, Tag2 & Tag3.

Upvotes: 0

wan.Lynnfield
wan.Lynnfield

Reputation: 27

Tags:
@foreach($article->tags as $tag)
    {{ $tags .= $tag->name . ', '; }}
@endforeach
{!! $tags !!}

I think you have to initialize $tags first...

Hope it helps.

Upvotes: -1

Related Questions