plenty of people have suggested (above) ways to iterate over multiple tags
@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
because you changed it to use ->first()
@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 }}
@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')) }}
@snapey the problem is that i am getting htmlspecialchars() expects parameter 1 to be string, array given after using
{{ explode(', ', $news->tags()->pluck('name')) }}
sorry, my mistake, explode converts string to array, we want array to string
{{ implode(', ', $news->tags()->pluck('name')) }}
@snapey another error implode(): Invalid arguments passed
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',', ') }}
@snapey yet another error Call to a member function implode() on null after trying this
{{ $news->tags->implode('name',', ') }}
so you probably have some item with no tags
use this instead
{{ implode(', ', $news->tags()->pluck('name'))->toArray() ?? [] }}
@snapey yeah i have some items with not tags.
still getting this error implode(): Invalid arguments passed
Does anyone have solution to this please?
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
@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>
Can anyone help with this.
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 Got this Invalid argument supplied for foreach()
You should eager load tags in the index method
Still having problems with it.
Please or to participate in this conversation.