在Laravel中替换''for' - '内部内爆查询

I have this piece of code that gets all subcategories for my article and includes them as CSS classes

<article class="{{ strtolower($a->subcategories->pluck('name')->implode(' ')) }} article-item">

Where $a is an Article model.

This works great except in case one of the categories having multiple words (a recent petition by my client).

Example:

Categories: 'home', 'ofice' and 'archive and storage'.

What I get:

<article class="home office archive and storage article-item">

What I want:

<article class="home office archive-and-storage article-item">

I hope with this my request is clear, how do I implode multiple words for each of my categories? I've tried to implode and str_replace() on various parts of the query builder but I can't get it right.

strtolower(implode(" ", str_replace(" ", "-", $a->subcategories->pluck('name')->all())));

This may not look too well, but it should work. At least, it worked for me with array ["a", "b a"] (producing "a b-a" output).

Maybe it can help you?

You need to map category name with spaces to that with dashes. With Laravel collections it's super easy. Just do:

{{ strtolower($a->subcategories->pluck('name')->map(function ($c) { return str_replace(" ", "-", $c); })->implode(' ')) }}

More on collection you can read here