Setting Bootstrap navbar active class in Laravel 5

Solution 1:

If you are working with named routes. You can use this approach in your views:

{{ Route::currentRouteNamed('about') ? 'active' : '' }}

or

{{ Route::is('about') ? 'active' : '' }}

The Illuminate\Routing\Router#is(...) is an alias of the Illuminate\Routing\Router#currentRouteNamed(...).

Solution 2:

Your code is working fine, but you have to use it for every link that can be active. It is better to return only class name, not class="..." so you can add other classes.

Be careful when using * at the end (about*). If you use /* for home page then it will always be marked as active (because every other page starts with /).

<ul class="nav nav-pills pull-right">
    <li class="{{ Request::is('/') ? 'active' : '' }}">
        <a href="{{ url('/') }}">Home</a>
    </li>
    <li class="{{ Request::is('about') ? 'active' : '' }}">
        <a href="{{ url('about') }}">About Us</a>
    </li>
    <li class="{{ Request::is('auth/login') ? 'active' : '' }}">
        <a href="{{ url('auth/login') }}">Login</a>
    </li>
</ul>

You can also move {{ Request::is('/') ? 'active' : '' }} to helper function/method.

Solution 3:

<ul class="nav nav-second-level">
                    <li class="{{ Request::segment(1) === 'programs' ? 'active' : null }}">
                        <a href="{{ url('programs' )}}" ></i> Programs</a>
                    </li>
                    <li class="{{ Request::segment(1) === 'beneficiaries' ? 'active' : null }}">
                        <a href="{{url('beneficiaries')}}"> Beneficiaries</a>
                    </li>
                    <li class="{{ Request::segment(1) === 'indicators' ? 'active' : null }}">
                        <a href="{{url('indicators')}}"> Indicators</a>
                    </li>                     
                </ul>

Solution 4:

Throw this in your helper.php

function set_active($path, $active = 'active') {

    return call_user_func_array('Request::is', (array)$path) ? $active : '';

}

Use it like so

<li class="{{ set_active(['about*']) }}"><a href="{{ url('about') }}">About Us</a>

You can pass a single string to a route or multiple and wildcards.

See more detail on Laravel Trick