Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

chas688's avatar

class conditional

One thing that's not well documented is a class conditional in blade - I've done it several ways, but using :class as a conditional and having a class="" as a base in this manner seems to work. I'm using a Tall stack. Where Livewire / Alpinejs shortcuts begin and blade ends, I'm still scratching my head. My question is, is this the 'better way' using this stack? Thx.

<nav class="-mb-px flex space-x-8" aria-label="Tabs">
		@foreach($subMenu as $menuItem)
        		<a href="{{ $menuItem['url'] }}"
                :class="{ ($menuItem['route'] == $selectSub) } border-b-2 border-indigo-500 text-indigo-600"
                class="whitespace-nowrap py-4 px-1 border-b-2 border-transparent font-medium text-sm text- gray-500 hover:text-gray-700 hover:border-gray-300">
				{{ $menuItem['label'] }}
				</a>
		@endforeach
</nav>
0 likes
2 replies
jaseofspades88's avatar
Level 51

You're wrong, it's documented quite clearly. Use the @class directive, documented here: https://laravel.com/docs/11.x/blade#conditional-classes.

Works like this...

@class([
	'bg-white', //this is always applied
	'border-red-500' => true,//this is applied because true
	'border-green-400' => false,//this is not applied because false
])

It's much cleaner than your example too... and will evaluate to the following...

class="bg-white border-red-500"
1 like
chas688's avatar

@jaseofspades88 That's just fantastic and easy to stick with Blade. Thanks for the post.

 		@class([
    		'whitespace-nowrap py-4 px-1 border-b-2 font-medium text-sm text-gray-500 hover:text-gray-700 hover:border-gray-300', //this is always applied
			'border-indigo-500 font-medium text-sm text-indigo-600' => ($menuItem['route'] == $selectSub),		 				
		])

Please or to participate in this conversation.