Getting current routes, controllers and action names in Laravel 4

March 08, 2014

In a lot of the projects I work on we use a customised version of Bootstrap to get the core layout work out of the way. Because of this, we often use the active class on various navigational elements to indicate which child should be highlighted. There are a couple of ways you could go about this, like comparing the current path to a given value, comparing the named route or inspecing the controller/action name that is in use. After using our own little helpers for a bit and later using the digithis/activehelper package, I was inspired to build Active with tests.

Active helps you determine whether you're on a given route or not. For example, you can test to see if you're on a certain path:

Active::is('posts/1'); // true

Simple. Now, what if you want to return a class name instead of a boolean value?

Active::path('posts/1'); // 'active'

Active::path(['posts/1', 'users/1']); //active

And if you want to use a custom class?

Active::path('posts/1', 'ready'); // 'ready'

Finally, all the same works for if you'd like to use named routes instead.

Active::route('posts.show', 'chickens'); // 'chickens'

Put together, it's really easy to create links that are active if the user is currently on that page.

<a href="{{ URL::route('posts.index') }}" class="{{ Active::route('posts.index') }}">All posts</a>


Active also ships with two helpers for getting the current controller and/or action name. This only works of course if you're in a controller/action, and not a closure.

// FooController@getBar
$controller = controller_name(); // foo
$action = action_name(); // bar

Let me know what you think of the package and if there is anything I can do to improve it. Open to suggestions and pull requests!

A blog about Laravel & Rails,
written by Dwight Watson.