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

t0berius's avatar

parsing active menue item to view

Dear community,

think we all know this problem. In a view you need to set for example the active link to be marked up ( class="active">), for easier navigation of user:

<ul class="nav nav-tabs">
    <li role="presentation" class="active"><a href="#">Home</a></li>
     <li role="presentation"><a href="#">Profile</a></li>
     <li role="presentation"><a href="#">Messages</a></li>
</ul>

How to get the "active" element / menue point? What's the best way to do so? Until now I haven't found a hint in laravel docs.

0 likes
5 replies
Pendo's avatar

What I was/am using for a couple of views is using named routes, for example:

Route::get('/profile/{user}', ['as' => 'user.profile', 'uses' => 'UserController@show']);

And then compare the current route name:

{{ Route::currentRouteName() == "user.profile" ? 'active' : '' }}

There might be another way to handle active items. But since I named all routes in my application, this keeps working even if I am going to change my URLs one day.

t0berius's avatar

Any other idea? I'm sure more can tell something about this, it's standart in webdev...

Snapey's avatar

You could define a variable in your blade template

    <?php $nav_profile = 'active'; ?>

    @extends ('layouts.app')

    @section ('content')
..
..
    @endsection

And then in the layouts file;

<ul class="nav nav-tabs">
    <li role="presentation" class="{{ $nav_home or ''  }}"><a href="#">Home</a></li>
     <li role="presentation" class="{{ $nav_profile or ''  }}"><a href="#">Profile</a></li>
     <li role="presentation" class="{{ $nav_messages or '' }}"><a href="#">Messages</a></li>
</ul>

So, if the page includes a variable called nav_profile then insert 'active' into the class. The 'or 'part inserts an empty string if the variable is not present.

Please or to participate in this conversation.