htmlcsslaravel-5bootstrap-4

Laravel - Add class to any nav-link if its generated url matches the current route


I'm working with Bootsrtap 4 and I'm trying to add the class active to my nav-item elements whenever their nav-link href attribute is the same as the current url.

On the html side, I uesd a basic url generator as shown below:

<ul class="navbar-nav">
    <li class="nav-item">
        <a class="nav-link" href="{{ url('/brands') }}" role="button">Brands</a>
    </li>

    <!-- ... -->
</ul>

And then I used a jQuery method to compare them with the current url:

$('.navbar-nav .nav-item .nav-link').each( () => {
    // If the current path and the link url are the same...
    if ($(this).attr('href').indexOf(location.pathname) !== 1) {
        // ...then add the class 'active' to 'nav-item', its parent
        $(this).parent().addClass('active')
    }
})

However, I noticed that $(this).attr('href') was undefined, probably because it's a generated url, and therefore nav-item doesn't get the active class.

As an example, for now it's a very basic url, without parameter, which looks like this: http://domain.example/brands


Solution

  • I'd recommend you to go another way. Instead of "activating" the link with jQuery, you could easily do it server-side with Laravel:

    <ul class="navbar-nav">
        <li class="nav-item">
            <a class="{{ Request::is('brands*') ? 'nav-link active' : 'nav-link' }}"
               href="{{ url('/brands') }}" 
               role="button">Brands</a>
        </li>
    
        <!-- ... -->
    </ul>
    

    Explanation:

    Laravel uses the template-engine twig for rendering the HTML server-side. Instead of manipulation the DOM client-side, you can easily add an conditional to check for the current request parameters. Laravel gives you nativeliy the possibility to check the request path even with a wildcard.