Skip to content

Laravel 4: Using Request::is() With Named Routes

Laravel Logo

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);
	}
}

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 named route:

{{ is_route('user.index') ? 'active' : '' }}

A named route with one or more parameters:

{{ is_route(['user.show', $user->id]) ? 'active' : '' }}

A named route with a wildcard:

{{ is_route(['user.show', '*']) ? 'active' : '' }}

And of course, multiple named routes:

{{ is_route('user.index', ['user.show', $user->id]) ? 'active' : '' }}

Comments

  1. Christopher Geary

    Bishal Paudel

    Thank you so much. This helped me a lot of future modification hours + a lot cleaner approach.

Have Your Say

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