Drupal - Get path alias from NID (or node object)
To get the path for a node id use AliasManager::getAliasByPath:
Drupal 8
$alias = \Drupal::service('path.alias_manager')->getAliasByPath('/node/'.$nid);
As per the new change record in Drupal 8.8.0 and above path.alias_manager
is deprecated and path_alias.manager
is introduced.
New syntax is as follows :
$url_alias = \Drupal::service('path_alias.manager')->getAliasByPath('/node/'. $nid, $langcode);
What about using Url:
use Drupal\Core\Url;
...
$url = Url::fromRoute('entity.node.canonical', ['node' => $nid])->toString();
If you only have the nid, 4k4's solution of
$alias = \Drupal::service('path.alias_manager')->getAliasByPath('/node/'.$nid);
Works great. But if you already have a node object you can skip a step or two. Nodes actually have built in methods for getting urls.
$node->toUrl()->toString();
Would return the aliased url of the node.
toUrl() returns a url object. See here https://api.drupal.org/api/drupal/core%21lib%21Drupal%21Core%21Url.php/class/Url/8.2.x
and toString() is a method of the url object that returns the string representation of the url.