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

AlokDev's avatar

How to make menu active on sublink?

In my project, I have 3 pages of two pages of the subpage of 1st page. I wanna make the sidebar menu active while accessing the subpages.

Here is my code.

Route::get('knowledge-base', 'PagesController@knowledge_base');

Route::get('knowledge-base/category', 'PagesController@kb_category');

Route::get('knowledge-base/category/question', 'PagesController@kb_question');

here is my link to make active in the side menu.

<a href="{{$menu->url}}" class="{{ url()->current() === url($menu->url) ? 'active' : '' }}">

Here is my side menu's JSON data.

{
      "url": "/page/knowledge-base",
      "name": "Knowledge Base"
    }

Please suggest to me how do I make my side-menu active on subpages.

1 like
2 replies
tisuchi's avatar
tisuchi
Best Answer
Level 70

@alokdev maybe you can set the name for each route and then check in the link.

For example-

Route::get('knowledge-base', 'PagesController@knowledge_base')->name('knowledge-base');

In the view-

<a href="{{$menu->url}}" class="{{ route()->currentRouteName() == 'knowledge-base' ? 'active' : '' }}">
5 likes
Kumaravel's avatar

First thing, make use of the named route. By naming your route, you can change your URL anytime without affecting any lines of code in the project.

You have to check it in the array, like {{ in_array(url()->current(), [$menu->url, $menu2->url, $menu3->url]) }}

Another way of using Javascript.

	<div id="test">
		<div class="btn active">Active Url</div>
		<div class="btn">Inactive</div>
		<div class="btn">Inactive</div>
		<div class="btn">Inactive</div>
	</div>

	<script>
		// Element is the main menu. And the childNodes is the Sub Menu here. But calling this within a function on page load it will add the 'active-menu' class in the main menu if any submenu contains 'active' class in it.
		let element = document.getElementById('test');
		let length = element.childNodes.length;
		for(i=0; i < length; i++) {
			if (element.childNodes[i].className.includes('active')) {
				element.classList.add('active-menu');
			}
		}
	</script>

4 likes

Please or to participate in this conversation.