Laravel 4: Using Request::is() With Named Routes
Recently I found myself trying to add an active css class to a navigation bar in a Laravel 4 project. Fortunately, much like everything in Laravel, there is a straightforward way to do it. I’m using named routes, as I don’t want to hardcode the URL structure throughout my application, and as far as I am aware, this how you would check the current URI against a particular route name.
Request::is(ltrim(route('users.show', [], false), '/'));
As you can see, it’s not very readable, and it’s a pain to type each time. After some tinkering, I came up with the following. It supports multiple route names, routes parameters and wildcards.
if( ! function_exists('is_route'))
{
/**
* Alias for Request::is(route(...))
*
* @return mixed
*/function is_route()
{
$args = func_get_args();
foreach($args as &$arg)
{
if(is_array($arg))
{
$route = array_shift($arg);
$arg = ltrim(route($route, $arg, false), '/');
continue;
}
$arg = ltrim(route($arg, [], false), '/');
}
return call_user_func_array(array(app('request'), 'is'), $args);
}
}
Named routes usage
In all the examples below I’ve included a ternary operator to output an active class (as a more real world usage example). You of course don’t need this if you’re only interested in the boolean value from the is_route()
function.
You can check the current URI against 1 route:
{{ is_route('user.index') ? 'active' : '' }}
With one or more parameters:
{{ is_route(['user.show', $user->id]) ? 'active' : '' }}
With a wildcard:
{{ is_route(['user.show', '*']) ? 'active' : '' }}
And of course, multiple named routes:
{{ is_route('user.index', ['user.show', $user->id]) ? 'active' : '' }}
If you have an interesting project and would like to discuss how we can help, contact us or give us a call 01442 877473.
Leave A Comment
Thank you so much. This helped me a lot of future modification hours + a lot cleaner approach.