Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

Snapey's avatar

plenty of people have suggested (above) ways to iterate over multiple tags

henryoladj's avatar

@snapey I selected more than tags for a post and after posting it, it is only one tag that is showing related to the post

Snapey's avatar

because you changed it to use ->first()

henryoladj's avatar

@snapey Yeah true, but what can i change it to so that it can show the two or more tags?

my code

{{ $news->tags()->first()->name }}
Snapey's avatar

@emadiga said

@foreach($news->tags as $tag)
{{ $tag->name }}
@endforeach

I suggested

{{ explode(', ', $news->tags->pluck('name')) }}

but I think it actually needs to be

{{ explode(', ', $news->tags()->pluck('name')) }}

henryoladj's avatar

@snapey the problem is that i am getting htmlspecialchars() expects parameter 1 to be string, array given after using

{{ explode(', ', $news->tags()->pluck('name')) }}
Snapey's avatar

sorry, my mistake, explode converts string to array, we want array to string

{{ implode(', ', $news->tags()->pluck('name')) }}
Snapey's avatar

It needs to be an array not a collection, try

{{ implode(', ', $news->tags()->pluck('name'))->toArray() }}

Above is the PHP function, but there is also a Laravel collection variant;

{{ $news->tags->implode('name',', ') }}
henryoladj's avatar

@snapey yet another error Call to a member function implode() on null after trying this

{{ $news->tags->implode('name',', ') }}
Snapey's avatar

so you probably have some item with no tags

use this instead

{{ implode(', ', $news->tags()->pluck('name'))->toArray() ?? [] }}
henryoladj's avatar

@snapey yeah i have some items with not tags.

still getting this error implode(): Invalid arguments passed

Snapey's avatar
Snapey
Best Answer
Level 122

Im surprised you get that error, because the implode has a bracket in the wrong place

{{ implode(', ', $news->tags()->pluck('name')->toArray() ?? [] )}}

You know its hard to get perfect, typing one fingered on an ipad. in this stupid little box. You have to be able to take the suggestions AND THINK FOR YOURSELF

henryoladj's avatar

@snapey It works now but how can i pass it in a link?

<a href="{{route('news.index', ['tag'=>$news->tags()->first()->url])}}">[ {{ implode(', ', $news->tags()->pluck('name')->toArray() ?? [] )}} ]</a>
Snapey's avatar

You cannot. But then I guess I should have anticipated you would say this, and tell you to use a foreach loop

@foreach($news->tags as $tag)
    <a href="{{ route('news.index',['tag'=>$tag->name]) }}">{{ $tag->name }}</a>
    @if(! $loop->last), @endif
@endforeach

Snapey's avatar

You should eager load tags in the index method

Previous

Please or to participate in this conversation.