8

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

12

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.

Your Answer

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

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