I've been wondering around looking for solutions, but can't really understand especially when creating helpers. I'm new in Laravel and I want a simple or if not a detailed instruction on how to set the active class for my bootstrap navbar.
Here's what I've done so far, but can't get it done:
<div class="header clearfix">
<nav>
<ul class="nav nav-pills pull-right">
<li class=""><a href="{{ url('/') }}">Home</a>
</li>
<li {{ Request::is('about*') ? ' class="active"' : null }}><a href="{{ url('about') }}">About Us</a>
</li>
<li><a href="{{ url('auth/login') }}">Login</a>
</li>
</ul>
</nav>
<h2 class="">Tobacco Prevention and Control Program</h2>
</div>
EDIT
Setting class="active"
will make all nav-pills active. The intended effect is that only the li
of the current page have the active
class.
EDIT
For those who are visiting this post. I have managed to get a solution, but I'm not sure if it is neat. Well it's working and fine for me.
<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>
Throw this in your
helper.php
Use it like so
You can pass a single string to a route or multiple and wildcards.
See more detail on Laravel Trick
use
Request::is('[level]') ? 'active' : ''
In case of multilevel, use:Request::is('[level]', '[level]/*') ? 'active' : ''
This is simple: to get your links to be active when using bootstrap, all you need is an if statement inside the class link, for instance: i have my current url as http://example.com/home
and you are good to go.
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/
).You can also move
{{ Request::is('/') ? 'active' : '' }}
to helper function/method.The solution given by @Daniel Antos is best answer, as I have found. Mr. Danial Antos also warned about using * at the end (about*). Because while using /* for home page then it is always marked as active (because every other page starts with /). So, I have used as follows and it worked fine for me:
If you are working with named routes. You can use this approach in your views:
or
The
Illuminate\Routing\Router#is(...)
is an alias of theIlluminate\Routing\Router#currentRouteNamed(...)
.