Skip to content

Instantly share code, notes, and snippets.

@crittermike
Forked from thagler/get_node_by_path.php
Created September 16, 2016 15:15
Show Gist options
  • Save crittermike/4e559ac299efe8485a256a6a144c77e3 to your computer and use it in GitHub Desktop.
Save crittermike/4e559ac299efe8485a256a6a144c77e3 to your computer and use it in GitHub Desktop.
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]);
}
@stloc
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