0

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.

1
  • keep your anchor tag outside the loop. Commented Oct 29, 2015 at 4:22

3 Answers 3

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

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

@endforeach
Sign up to request clarification or add additional context in comments.

Comments

0

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.

Comments

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

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

Hope it helps.

5 Comments

Laravel said no,no: ErrorException in 738b47fc71d167c6de0d1e03eb6984b6 line 18: Undefined variable: tags (View: /home1/carwars/laravel/resources/views/page/article.blade.php)
PS I even added <?php $tags = array(); ?> before the loop and the result was the same. So no.
I would but the idea here is to use the Laravel Active Records and blade functionality, so this means no plain php code is a solution here.
Why don't you pass your $tags value from your controller? You could simply do it right?
Yes this was the solution. However I believe there could be another approach.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.