Laravel 5: Adding active class to bootstrap navbar links


There are several ways in adding active class to your Bootrap navigation bar. I'll share MY way of doing it and I find it simple and not having problem at all (unless you have super multi-level navigation bar). Bootrap has 'active' class that allows user to see which pages he is on. This serves as page indicator as well.



<div class="header clearfix">
        <nav>
          <ul class="nav nav-pills pull-right">
            <li class="{{ Request::segment(1) === null ? 'active' : null }}"><a href="{{ url('/') }}">Home</a></li>
            <li class="{{ Request::segment(1) === 'about' ? 'active' : null }}"><a href="{{ url('about') }}">About Us</a></li>
            <li class="{{ Request::segment(1) === 'auth' ? 'active' : null }}"><a href="{{ url('/dashboard') }}">
                    @if(Auth::check())
                        Dashboard
                    @else
                        Login
                    @endif
                </a>
            </li>
        </ul>
    </nav>
    <h2 class="">Tobacco Prevention and Control Program</h2>
</div>

Doing this in Laravel is easy, you just have to identify the segment of your page. The Request::segment(1) === 'about' is the first segment of your application which means new slash will be another segment number.


@if(Auth::check()) Checks whether the user is logged in. And if logged-in it will change the login link to 'Dashboard'.

pretty cool!

Labels: