Active menu state using route attributes

I bet you have a headache when you need to mark some menu item as active. Is there any good way to solve this? Yes, there is – route attributes.

What is route attributes? Standard route attributes are like “prefix”, “namespace”, “as”, “uses” and others, for example:

As you can see route group has attributes (prefix, as), this routing feature enables us to add our custom route attributes like “_active_menu”.

In the example above I have added new route attribute (_active_menu), keep in mind that these attributes can be used on single routes as well. And now this can be injected into views using Laravel view composer.

By now we have defined a custom route attribute, created new composer class for injecting custom parameter into our views. Next step is to register our new and shiny composer class.

Don’t have service provider for view composers in your project? Read about it here.

8 thoughts on “Active menu state using route attributes”

    1. I decided to use this approach because I had to define same active menu states for different routes, it depends on project structure.

  1. This is a nice solution! Thanks for sharing, like you said, there are different approaches and I have had instances where this approach would be the better solution then currently implemented.

  2. Just a quick comment, I implemented it in a project and made a small change.

    $view->with(‘active_menu’, (array_key_exists(‘active_menu’, $routeAction)) ? $routeAction[‘active_menu’] : null);

    I have a top navigation using active_menu, but I have some pages that don’t have top navigation link or active state, which gave an error.

    I used this in the view:

    What do you use?

    Thanks again!

Leave a Reply

Your email address will not be published. Required fields are marked *