Automatically highlight nav links

Automatically highlight nav links when exact URL matches, or pass a path or route name pattern.

A Blade component with request and CSS classes helpers makes it ridiculously simple to show active/inactive state.

1class NavLink extends Component
2{
3 public function __construct($href, $active = null)
4 {
5 $this->href = $href;
6 $this->active = $active ?? $href;
7 }
8 
9 public function render(): View
10 {
11 $classes = ['font-medium', 'py-2', 'text-primary' => $this->isActive()];
12 
13 return view('components.nav-link', [
14 'class' => Arr::toCssClasses($classes);
15 ]);
16 }
17 
18 protected function isActive(): bool
19 {
20 if (is_bool($this->active)) {
21 return $this->active;
22 }
23 
24 if (request()->is($this->active)) {
25 return true;
26 }
27 
28 if (request()->fullUrlIs($this->active)) {
29 return true;
30 }
31 
32 return request()->routeIs($this->active);
33 }
34}
1<a href="{{ $href }}" {{ $attributes->class($class) }}>
2 {{ $slot }}
3</a>
1<x-nav-link :href="route('projects.index')">Projects</x-nav-link>
2<x-nav-link :href="route('projects.index')" active="projects.*">Projects</x-nav-link>
3<x-nav-link :href="route('projects.index')" active="projects/*">Projects</x-nav-link>
4<x-nav-link :href="route('projects.index')" :active="$tab = 'projects'">Projects</x-nav-link>

Tip given by @mpskovvang

Like our articles?

Become a Premium Member for $129/year or $29/month
What else you will get:
  • 22 courses (477 lessons, total 38 h 20 min)
  • 2 long-form tutorials (one new every week)
  • access to project repositories
  • access to private Discord