How do I get a node ID using slug?

by Lhassan Baazzi   Last Updated December 19, 2017 11:07 AM

I have a node whose slug is /node-21-company-name; I want to get the ID associated with this slug. How do I achieve this?

I know how to get the node entity by ID Node::load(id).

Tags : nodes entities 8


Answers 2


I found a solution, but I don't think if it's a good solution, I have used this code in a parameter converter:

use Drupal\Core\Url;

$url = Url::fromUserInput('/node-21-company-name');
$params = $url->getRouteParameters();

if ($params && array_key_exists('node', $params)) {
    $storage = \Drupal::entityManager()->getStorage('node');
    $company = $storage->load($params['node']);
    return $company;
}
Lhassan Baazzi
Lhassan Baazzi
December 01, 2015 16:14 PM

$current_uri = \Drupal::request()->getRequestUri();
$path = \Drupal::service('path.alias_manager')->getPathByAlias($current_uri);
    if(preg_match('/node\/(\d+)/', $path, $matches)) {
       $node = \Drupal\node\Entity\Node::load($matches[1]);
    }
Fouèd Moussi
Fouèd Moussi
December 19, 2017 10:43 AM

Related Questions



Is it possible to disable the Node module?

Updated April 19, 2015 20:03 PM

Changing a node's content type

Updated May 01, 2016 08:03 AM


How do I fix this issue with space

Updated March 20, 2017 22:07 PM