Getting node URL path using entity query in Drupal

In this blog post, we'll explore how to get a node URL path using entity query in Drupal. We'll discuss different methods to generate URL strings and provide examples.

Fetching Node Title and Path

The initial code snippet provided shows how to fetch the title of a node using an entity query:

$query = $query->get('node')
  ->condition('status', 1, '=')
  ->condition('type', 'articles')
  ->condition('field_category', 'Technology', '=')
  ->sort('created', 'DESC')
  ->execute();

foreach ($techArticles as $key => $article) {
  $articleNode = _nodeLoad($article);
  $variables['tech_articles'][$key]['title'] = $articleNode->get('title')->value;
  $variables['tech_articles'][$key]['path'] = $articleNode->get('path')->value;
}

To get the URL path for the node, there are several ways to generate the URL string, \Drupal\Core\Url object, \Drupal\Core\Link object, or an HTML string for the link.

Generating URL Strings and Objects

To get the \Drupal\Core\Url object for the node:

$node->toUrl();

To get a URL string:

$node->toUrl()->toString();

To get a \Drupal\Core\Link object:

$node->toLink();

To get an HTML string for the link:

$node->toLink()->toString();

Customizing the Node Link

toLink() can optionally take an argument providing a different node link. For example, you can generate a link to the node edit or delete page: To get a link to the node edit page:

$node->toLink('edit-form');

To get a link to the node delete page:

$node->toLink('delete-form');

The values that can be passed to toLink() can be determined by looking at the keys of the links section of the annotation for the entity type. The node class lists these as:

*  links = {
*    "canonical" = "/node/{node}",
*    "delete-form" = "/node/{node}/delete",
*    "delete-multiple-form" = "/admin/content/node/delete",
*    "edit-form" = "/node/{node}/edit",
*    "version-history" = "/node/{node}/revisions",
*    "revision" = "/node/{node}/revisions/{node_revision}/view",
*    "create" = "/node",
*  }

Retrieving the Alias Using the Node ID

Once you have the node ID, you can retrieve the alias using the following code:

$alias = \Drupal::service('path.alias_manager')->getAliasByPath('/node/' . $nid);

 

Saved you some valuable time?

Buy me a drink 🍺 to keep me motivated to create free content like this!