How to get the current path alias or path in Drupal


When migrating a Drupal 7 site to Drupal 9, working with path aliases in custom code is something that is often required. Path aliases were converted to revisionable entities in Drupal 8.8, so also when upgrading from older versions of Drupal 8 the handling of path aliases has changed quite a bit.

Published on May 13, 2022

In order to get an alias, if one is available, we first need the current path. In Drupal 9 we use a service for that:

$current_path = \Drupal::service('path.current')->getPath();

We then use the path_alias.manager service introduced in Drupal 8.8 by calling the getAliasByPath() method on it and feeding it the $current_path we got earlier. This basically does what drupal_get_path_alias() did in Drupal 7 and it replaces the legacy service path.alias_manager in older versions of Drupal 8. So execute the following will get you the alias based on the path provided:

$result = \Drupal::service('path_alias.manager')->getAliasByPath($current_path);

Depending on the kind of processing you want to do, you can now check if there is an alias in the system for the path you are checking. If no alias is found you can fall back to the raw value of the path, the value of $current_path. So all you need to do in order to get the path alias is execute the following code:

$current_path = \Drupal::service('path.current')->getPath();
$result = \Drupal::service('path_alias.manager')->getAliasByPath($current_path);

One important remark

If your code is checking whether the request is on a specific path structure, it is better to rely on routes than on paths. Drupal 9 uses Symfony for its routing, this provides a more robust way to map resources that is independent of path structures. To do this you can use the routeMatch service available.

If, for example, you want to check if you're in the /user/xxx url, you could do:

if (\Drupal::routeMatch()->getRouteName() === 'entity.user.canonical')

This would provide a robust check that you are on the route you are expecting to be on, after that you can perform further checks on the path (check that xxx is indeed the uid you want for instance). 


Hopefully this provides some clarity on handling path aliases in Drupal 9! Please don't be afraid to reach out if you need any help with your Drupal project. Our experts are always happy to help!

drupal 8
drupal 9
planet drupal