In order to load the canonical path of an entity we first need to check that the entity has that path available using the hasLinkTemplate() method. If it does then we can get the path for the entity.
if ($entity->hasLinkTemplate('canonical')) {
// Relative path, e.g. "/node/123" or /about-us.
$path = $entity->toUrl('canonical')->toString();
}The full URL can be retrieved using the same method.
if ($entity->hasLinkTemplate('canonical')) {
// Full absolute URL, e.g. "https://example.com/node/123".
$absolute = $entity->toUrl('canonical', ['absolute' => TRUE])->toString();
}Or, we can get the internal path using the getInternalPath(), which can be used to find the aliases for the path.
if ($entity->hasLinkTemplate('canonical')) {
// The internal path, e.g "node/123".
$internalPath = $value->toUrl('canonical')->getInternalPath();
}
Add new comment