DEV Community

Hamid Haghdoost
Hamid Haghdoost

Posted on • Updated on

Activate links of Laravel Blade based on current route name

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:
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.

Top comments (2)

jsn1nj4 profile image
Elliot Derhay • Edited

Funny, I actually did do that with Route::currentRouteName().

If this package is mostly adding a blade directive, that can be done here also:

I mention this in case anyone is averse to adding a package for something this small.

haamid profile image
Hamid Haghdoost

Thank you for your comment. Yes, actually I have extended a custom directive in this package. I have several purposes for this package.

First I wanted to write a package to be familiar with aspects of package development in Laravel like:

  • Testing
  • Versioning
  • Binding to IOC
  • Publishing the config files
  • Making the Facades
  • ...

And I hope to make it better and add some other features in future.

And I will be happy to hear your suggestions and maybe contributions :)