What is the best way to highlight an active menu item ? i have my menu, and i need to highlight the selected item (current route)
what is the best way to do this in laravel ? check the routes on in the base controller ?
In blade template :
<a href="#" class="{{ (\Request::route()->getName() == 'this.route') ? 'active' : '' }}">
I used to do this manually in the controller methods in previous sites (not Laravel based)..
public function fooAction() {
return [
'activePage' => 'home'
];
}
for example, and then in the layout file, add conditionals for classes in the menu item:
class="<?php if ('home' === $activePage):?>menu-item-active<?php endif;?>"
etc etc etc.
Cheers..
Ian
EDIT: Nice elegant solution @pmall =)
You can also use a view composer to pass the current route name to the view. In AppServiceProvider boot method :
public function boot ()
{
view()->composer('*', function ($view) {
$current_route_name = \Request::route()->getName();
$view->with('current_route_name', $current_route_name);
});
}
I found this class as very usefull and clean solution- https://github.com/lavary/laravel-menu . Using that you can put in your routes/web.php menu like that:
Menu::make('Menu', function($menu){
$menu->add('Home', 'index');
$menu->add('Customers', 'customers')->active('customers/*'); //active() makes that also any subroutes are active, ex: customers/{id}/edit
...
});
I believe this is simple way to show active menu.
class="{{ ((Request::is('XX/XX/*')) ? 'active' : ' ') }}
@pmall can you please clear your answer more
say I have this menu item and I need to do active
<li>
<a href="{!! URL::route('services.index') !!}"><i class="fa fa-plus"></i>{!! trans('interface.services') !!}</a>
</li>
and I need to add active as a class to it like
<li>
<a class="active" href="{!! URL::route('services.index') !!}"><i class="fa fa-plus"></i>{!! trans('interface.services') !!}</a>
</li>
How to do that??
Thanks
This works if your using named routes:
<li class="nav-item {{ Route::currentRouteNamed( 'contact' ) ? 'active' : '' }}">
<a itemprop="url" class="nav-link" href="{{route( 'contact')}}">
Contact Us
</a>
</li>
Hope this helps someone
@willeums I like your solution, but I don't see how it can work if the
is a submenu or a larger menu system. How can you assign the "active" state to the parent menu item?
Willeums' solution is the most readable that I've seen so far. 👌
Please sign in or create an account to participate in this conversation.