In Drupal 8, I need to verify a route exists or not in a custom module. How can I achieve this?

/* @var \Drupal\Core\Routing\RouteProviderInterface $route_provider */
$route_provider = \Drupal::service('router.route_provider');

RouteProviderInterface::getRouteByName() returns a \Symfony\Component\Routing\Route object if it exists, or throws an exception if it does not.

You can use RouteProviderInterface::getRoutesByNames() if you don't want an exception.

$exists = count($route_provider->getRoutesByNames(['abc.xyz'])) === 1;
  • Notice that getRoutesByNames() can still raise an exception, if it gets an empty array as parameter. In the case of dynamically created arrays, it's better to trap the exception, or verify the array passed to the method is not empty. – kiamlaluno Dec 10 '16 at 10:12
  • Thanks aton @daniel & Kiamlaluno for helping out of this... – harsh_behl_0007 Dec 12 '16 at 4:44
  • Thanks for the testing method! I have added a core issue to add this as a method to RouteProvider: drupal.org/project/drupal/issues/3029545 – oknate Feb 1 '19 at 15:57

To check route exist or not use below function:

function routeExists($name)
    // I assume that you have a link to the container in your twig extension class
    $router = $this->container->get('router');
    return (null === $router->getRouteCollection()->get($name)) ? false : true;
  • 1
    Since the code is using $this, that is not a function, but a method of a class. You don't say which class, exactly. – kiamlaluno Dec 10 '16 at 9:27
  • 1
    Also, (null === $router->getRouteCollection()->get($name)) ? false : true is unnecessarily complicated. There is no need of a ternary operation, since === returns already a boolean. – kiamlaluno Dec 10 '16 at 10:14

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.