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

lanzalf's avatar

Dynamic Nav Menu

Hi there

I am working on my first Laravel project.

I have a navigational menu for my project which has active and inactive tabs. When a tab is active then I need to set the class to active. For example there is a tab for Settings. Then underneath settings there is a sub menu for Staff.

Currently my static html code for the menu sits in the layouts directory in views. I’m having trouble trying to figure out how to make this dynamically change based on the view the user is in.

Previously on my non Laravel php site, I made the menu a function that I would pass parameters to. So I would do:

mainMenu(“settings”, “staff”);  

It would just look at the parameters and return me the menu code with the menu and and its sub menu classes active.

I’m struggling with the idea of how I could implement this into a Laravel project.. I guess I am looking for a way to dynamically update a html class based on the URL. And where I would put the PHP logic so that it could be accessed sitewide.

Many thanks for any suggestions or assistance!

0 likes
2 replies
Snapey's avatar
Snapey
Best Answer
Level 122

one way is to test the url in-line

          <ul class="nav navbar-right nav-pills speakernav">
            <li><a href="/talks" @if(request()->segment(1)=='talks') class="active" @endif >Browse Talks</a></li>
            <li><a href="/newtalk" @if(request()->segment(1)=='newtalk') class="active" @endif >Post a Talk</a></li>
            <li><a href="/register" @if(request()->segment(1)=='register') class="active" @endif >
                @if(Auth::check()){{ Auth::user()->name }} @else Login @endif</a></li>
          </ul>

The segment(1) part returns the first part of the path and ignores any parameters, eg /talks/edit

So the test if the link should be active is in-line in the menu partial or master layout.

You can do similar with named routes.

There are also a lot of packages available that can do some of the work for you; https://packagist.org/search/?q=laravel%20active%20menu

lanzalf's avatar

I think this is exactly what I am looking for! Thank you so much :) .. Much simpler than I had imagined.

Please or to participate in this conversation.