In this section, we’ll explore how to use the active class for links in Laravel. We’ll demonstrate how to indicate active link routes in Laravel using Tailwind CSS and Bootstrap 5.
Example 1
A simple way to add an active class to links in Laravel 9 is by using request()->is('/')
along with a ternary operator.
<li>
<a href="/" class="{{ request()->is('/') ? 'text-blue-600':'' }}">Home</a>
</li>
<li>
<a href="{{ route('vuejs') }}" class="{{ request()->is('vuejs') ? 'text-green-600':'' }}">Vue</a>
</li>
Example 2
Utilize routeIs
to generate active links for current routes.
<li>
<a href="/" class="{{ request()->routeIs('/') ? 'text-blue-600':'' }}">Home</a>
</li>
<li>
<a href="{{ route('vuejs') }}" class="{{ request()->routeIs('vuejs') ? 'text-green-600':'' }}">Vue</a>
</li>
Example 3
You can also employ Laravel’s @class
directive to add active link classes to Tailwind CSS navbar links.
<li>
<a href="{{ route('vuejs') }}" @class(['text-blue-600'=> request()->is('vuejs') ])>Test</a>
</li>
Example 4
Laravel active routes links with bootstrap 5.
<li class="nav-item">
<a class="nav-link {{ request()->routeIs('/') ? 'active':'' }}" aria-current="page" href="/">Home</a>
</li>