How to echo project tags for each project in the list of all projects?

I would like to add one or more classes to each project in the list of all projects. Those classes being the tags that the project has.

What I have now in my template:

<?php foreach($projects as $project): ?>
    <article class="collection-item <?php foreach($tags as $tag): echo $tag; endforeach ?>">
        <header>
        ...

And in my controller:

return function($site, $pages, $page) {
  ...
  // fetch all tags
  $tags = $projects->pluck('tags', ',', false);
  ...
  return compact('projects', 'tags', 'tag', 'pagination');

However the output is:

<article class="collection-item architectuurarchitectuurontwikkeling">
    <header>

This particular project only has the tags ‘architectuur’ and ‘ontwikkeling’. It looks like architectuur is being output twice. This probably means all tags from all projects are being loaded.

What am I doing wrong?

Two things:

  1. In your controller you fetch all tags of all projects and then apply all these tags to the single project. This doesn’t seem to be what you want.

  2. You don’t have a space between your tags

Solution:

<?php foreach($projects as $project): ?>
  <?php 
    // get array of tags from single project
    $projectTags = $project->tags()->split(',');
   ?>
    <!-- use implode() to split the array into a string separated by spaces -->
    <article class="collection-item <?= implode(' ', $projectTags) ?>">
    </article>
<?php endforeach ?>

Ah, I was using $project->tags() before, but figured I should just use the $tags from the controller instead.

Currently I’ve got

    <?php foreach($projects as $project): ?>
        <?php $projectTags = $project->tags()->split(','); ?>
        <article class="collection-item <?php implode(' ', $projectTags) ?>">
            <header>

But the output is:

<article class="collection-item ">
    <header>

So I’m not 100% there yet, but I don’t really know php well enough to be able to debug this correctly. But in any case thanks so much for the super fast reply! (Support at 23:00 on a Sunday? Amazing!)

Oh, forgot the echo()

<article class="collection-item <?= implode(' ', $projectTags) ?>">

D’oh, of course.

Thanks so much once more!