Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Drupal 8 Get node ID by path alias
<?php
$path = \Drupal::service('path.alias_manager')->getPathByAlias('/this-is-the-alias');
if(preg_match('/node\/(\d+)/', $path, $matches)) {
$node = \Drupal\node\Entity\Node::load($matches[1]);
}
@MyMarvel

This comment has been minimized.

Copy link

@MyMarvel MyMarvel commented Jul 18, 2019

It doesn't work for translated entities.

@JackFrost

This comment has been minimized.

Copy link

@JackFrost JackFrost commented Oct 30, 2019

You can do it with:
$url_object = \Drupal::service('path.validator') ->getUrlIfValid('/en/this-is-the-alias');
$route_name = $url_object->getRouteName();
$route_parameters = $url_object->getrouteParameters();

@rockymountainhigh1943

This comment has been minimized.

Copy link

@rockymountainhigh1943 rockymountainhigh1943 commented Nov 18, 2019

@JackFrost thanks! That answer worked for me and returned the node ID exactly as I wanted it :-)

@stloc

This comment has been minimized.

Copy link

@stloc stloc commented Dec 5, 2019

  public function nodeBySlug($slug) {
    $database =  \Drupal::database();
    $query = $database->query(
      "SELECT nid
            FROM {node} n, {url_alias} a
            WHERE n.nid = SUBSTR(a.source, 7)
            AND a.alias = '/$slug'"
    );
    $result = $query->fetchObject();
    if ($result !== false) {
      $node = Node::load($result->nid);
      return new JsonResponse($node->toArray());
    }

    //return new JsonResponse(json_encode(false));
    return new JsonResponse(false);
  }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment