Activate links of Laravel Blade based on current route name

Hamid Haghdoost - May 13 '22 - - Dev Community

Consider a navigation menu with a bunch of links and you are trying to activate them based on the current active route name. In normal case you have to return the currentRouteName() from the controller or maybe in view composer or any other place. I have wrote a simple Laravel composer package that makes it a little bit simpler.
You can take a look it here: https://github.com/tuytoosh/active.
For installation use composer require command like this:

composer require tuytoosh/active

Enter fullscreen mode Exit fullscreen mode

Then use @active() directive in your blade files.

<a href="#" class="@active('home')">Home page</a>

Enter fullscreen mode Exit fullscreen mode

Without this package you have to write sth like this:

<a href="#" class="@if(Route::getCurrentRouteName() == 'home') active @endif">Home page</a>

Enter fullscreen mode Exit fullscreen mode

After version 1.7.0 You are able to define an array of route patterns like this:

class="@active(['admin.dashboard', 'user.dashboard'])"
Enter fullscreen mode Exit fullscreen mode

If you find it use full give a star :)
Thank you for reading.

. . . . . . . . . . .