How to get path alias and arguments in Drupal 8?

May 09, 2016 - 07:31

In Drupal 7, the function drupal_get_path_alias is used to get the path alias from internal path and arg function is used to get arguments from url. But both these functions are deprecated in Drupal 8.

Drupal 8 uses service container to access various services such as sending an email, accessing a database etc. This ensures that a decoupled nature of the system is respected. We will use the services of current path and path alias to get the result.

Service and Service container
  • Service : any PHP object that performs some sort of general task.
  • Service Container : a PHP object that manages the creation of those services.

Configuration for the services are defined in a yaml file. Service Container constructs the services according to this configuration. A service is constructed only when it is called using a service container. So the services will not affect the performance even if it is not used in the current application. A very detailed explanation about the service container can be found in the symfony docs.

We use path.current service to get the current path and path.alias_manager service to get the alias path from the internal path.

$current_path = \Drupal::service('path.current')->getPath(); // Gets internal path - for eg /node/29.
$path_alias = \Drupal::service('path.alias_manager')->getAliasByPath($current_path, $langcode);

We can get the path arguments from current path by exploding the current path and getting it in an array.

$current_path = \Drupal::service('path.current')->getPath(); // Gets internal path - for eg /node/29.
// Retrieve an array which contains the path pieces.
$pathArgs = explode('/', $current_path);

Another way to get path is by using URL class. Put the URL namespace at the top.

use \Drupal\Core\Url;

$currentUrl = Url::fromRoute('<current>');
$path = $currentUrl->getInternalPath();
// Retrieve an array which contains the path pieces.
$pathArgs = explode('/', $path);

You could also use request static class to get the request object and get the path. But this is discouraged since most programs should not need to access request object directly.

$current_uri = \Drupal::request()->getRequestUri(); //current aliased path