Setting active state in a navbar link

What's so special about navbar/sidebar ?

It can be seen that almost all the websites have a navigation bar with many items for front end. For example there can be navigation items as follows

  • Home
  • About us
  • Blog
  • Contact us

these are just common examples of navigation bar items. The same happens even if we have a sidebar , where it has tabs for navigation . when these links are clicked, it will direct us to the corresponding page.

Enhancement to navbar items for better user experience

The thing to notice here is, the sidebar/navbar is there almost all the having separate html code for each page would be enough so that we can show the same navbar/sidebar in all the pages. For the better user experience the current navbar item is normally enhanced by underlining the navbar item , or having some sort of special css class to make it unique from others. This routine is followed in almost all the websites.

Assume that we have a css class called active to enhance the current navbar item. This class can be applied to the particular item when we use separate code for each page. but the problem is the efficiency, imagine when it's required to change a particular text, it has to be done in all the files.

But when it comes to PHP we can have dynamic content as we want. since the same code is duplicated in many places, it can be extracted to a single file and included where necessary. The same concept can be applied for Footers as well , since they also appear in all the pages. But then we need to make sure we give the same user experience as before ( enhancing the current navbar item ).

Basically it drops down to a simple problem of detecting the page and add a class called active to the corresponding page.

Lets Try it with Laravel

we can easily detect the current page using the routes, in Laravel can use the following helper


We can extract the code for the navbar to a blade file and add it in the /resources/views/layouts

Assume the filename to be Navbar.blade.php

After adding the html code to the blade file, we an use Ternary Operator in PHP to make the decision to whether to add the active class or not , following code shows a sample content of Navbar.blade.php

<ul class="nav navbar-nav">
    <!-- items for nvbar-->
    <li class="{{request()->is('/') ? 'active' : ''}}">
         <a href="/">Home</a>
    <li class="{{request()->is('blog') ? 'active' : ''}}">
         <a href="/blog">Blog</a>

Include the blade file where necessary


for more information on including content dynamically, check the official documentation of Laravel


Avoid code duplication as much as possible and achieve the flexibility needed through these kind of methods. always have the habit to extract code and minimize the overhead.

Related articles

Signature Pad with Alpine.js

The post describes the implementation of signature pads with Alpine.js. It also discusses how to integrate it with laravel livewire.