October 14th, 2023

Laravel Blade's `@class` Directive

In most of the Blade front-ends I build I create a classes() helper function. Basically, take an array or parameter list of nullable strings and then filter and join them. Something like this:

1function classes(...$classes): string
2{
3 return collect($classes)->filter()->join(' ');
4}

It’s useful in scenarios when the CSS classes you want applied to an element will be different given some context.

1<ol>
2 @foreach ($todos as $todo)
3 <li class="{{ classes('todo-item', $todo->completed ? 'line-through' : '', $todo->sticky ? 'bg-yellow-100' : '') }}">
4 Walk the dog
5 </li>
6 @endforeach
7</ol>

As is so often the case, I discovered Laravel has a built in @class directive designed for this exact scenario, and as per usual, their syntax is nicer than mine.

1<ol>
2 @foreach ($todos as $todo)
3 <li @class([
4 'text-lg',
5 'line-through' => $todo->completed,
6 'bg-yellow-100' => $todo->sticky,
7 ])>
8 Walk the dog
9 </li>
10 @endforeach
11</ol>

Under the covers, this is just a wrapper for Arr::toCssClasses() which is what you’ll want to reach for when using inside $attributes->merge([...]) in Blade components. There’s also an Arr::toCssStyles() helper.