Skip to content

Instantly share code, notes, and snippets.

Forked from thagler/get_node_by_path.php
Created September 16, 2016 15:15
  • Star 11 You must be signed in to star a gist
  • Fork 3 You must be signed in to fork a gist
Star You must be signed in to star a gist
Save crittermike/4e559ac299efe8485a256a6a144c77e3 to your computer and use it in GitHub Desktop.
Drupal 8 Get node ID by path alias
$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]);
Copy link

It doesn't work for translated entities.

Copy link

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();

Copy link

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

Copy link

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