-
-
Save crittermike/4e559ac299efe8485a256a6a144c77e3 to your computer and use it in GitHub Desktop.
Drupal 8 Get node ID by path alias
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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]); | |
} |
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();
@JackFrost thanks! That answer worked for me and returned the node ID exactly as I wanted it :-)
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
It doesn't work for translated entities.