DEV Community

Hamid Haghdoost
Hamid Haghdoost

Posted on • Edited on

7 3

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

Image of Timescale

🚀 pgai Vectorizer: SQLAlchemy and LiteLLM Make Vector Search Simple

We built pgai Vectorizer to simplify embedding management for AI applications—without needing a separate database or complex infrastructure. Since launch, developers have created over 3,000 vectorizers on Timescale Cloud, with many more self-hosted.

Read more

Top comments (2)

Collapse
 
jsn1nj4 profile image

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

If this package is mostly adding a blade directive, that can be done here also: laravel.com/docs/9.x/blade#extendi...

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

Collapse
 
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 :)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more