Tag slugs displayed as classes or data attributes of an element

Hi there,
I have a foreach which displays titles and some other information from all the child pages of a certain parent. Each page has some tags (named “category”) assigned (wjth a “tags” type field).
I am trying to list all the tags assigned to a page as a data attribute values to the div which contains each child page.

The result should be like this:
<div class="article" data-tags="photography interaction-design architecture web-design">
<p>Article title</p>

I am using this inside the data-tag attribute to achieve this result:
<?php foreach ($item->category()->slug()->split(",") as $category): ?><?= $category ?><?php endforeach ?>

This is the result I get:

I see two problems here:

  • The tags are not separated by spaces when they are displayed as slugs (everything is merged as a unique tag).
  • There is no distinction between single-word tags and multiple-word tags.

I tried other ways but (with no luck) but this seemed the more correct one to me.

Do you have any suggestions?

It doesn’t make sense to call split on the sluggified tags field.

$tags = array_map(function($tag) {
  return Str::slug($tag);
}, $item->category()->split(','));

echo implode(' ', $tags);

It works like a charm! Thank you!
I was using the wrong approach.

And is there a way to display all the tags assigned to all the pages without duplicates?

<?php foreach($items as $item): ?>
   <?php $tags = array_map(function($tag) {
        return Str::slug($tag);
   }, $item->category()->split(',')); ?>
   <?php echo implode(' ', $tags); ?>
<?php endforeach ?>

This solution keeps all the duplicates.

Thanks for your help!

To get all tags from all pages you can use the pluck() method with the third parameter set to true:

$allTags = $items->pluck('category', ',', true);

But if you use this inside the loop, then you will get all tags for all the pages multiple times, which doesn’t make sense.