9

If I have a Url object, or even a simple string representation of path such as /node/2, how can I get the full Route object?

1 Answer 1

13

You can retrieve this information from the Symfony router. This can be accessed in Drupal through the router.no_access_checks service.

If you have a simple path (note that the path has a leading slash):

$router = \Drupal::service('router.no_access_checks');
$result = $router->match('/node/2');

If you have a Url object:

$router = \Drupal::service('router.no_access_checks');
$result = $router->match($url->toString());

This will return an array that includes the route object, as well as other useful information such as the route name and route parameters, the controller, the title callback and even the entity object represented by the URL.

1
  • To get just the route string: drush eval "echo \Drupal::service('router.no_access_checks')->match('/some/path')['_route'];
    – mbomb007
    Commented Jun 28 at 16:15

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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