How to create a link from node ID in Drupal 8?

Posted by Rohit Kumar | Updated on

How to create a link from node ID in Drupal 8? You need to use the \Drupal\Core\Url class, specifically its fromRoute static method. Drupal 8 uses routes which have name different from their actual URL path. In your case, the route to use is the canonical route for a node entity: entity.node.canonical. \Drupal\Core\Url::fromRoute() will not return a string, but an object. To get the URL as a string, you need to call its toString() method.

The static method is not easily testable, $url->toString() require an initialized container. Your can replace the static method with a call to UrlGeneratorInterface::generateFromRoute() on the url_generator service.


If you like this question & answer and want to contribute, then write your question & answer and email to freewebmentor[@]gmail.com. Your question and answer will appear on FreeWebMentor.com and help other developers.

Related Questions & Answers