Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

elieandraos's avatar

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 ?

0 likes
12 replies
pmall's avatar

In blade template :

<a href="#" class="{{ (\Request::route()->getName() == 'this.route') ? 'active' : '' }}">
3 likes
ian_h's avatar

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 =)

pmall's avatar
pmall
Best Answer
Level 56

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);

    });
}
7 likes
wizjo's avatar

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
    ...
    
});
1 like
deveshpandyadc's avatar

I believe this is simple way to show active menu.

class="{{ ((Request::is('XX/XX/*')) ? 'active' : ' ') }}

6 likes
johnef_sh's avatar

@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

1 like
willeums's avatar

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

5 likes
phayes0289's avatar

@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?

  • shanedeconinck's avatar

    Willeums' solution is the most readable that I've seen so far. 👌

    1 like

    Please or to participate in this conversation.