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).

closed as unclear what you're asking by kiamlaluno May 23 at 11:20

Please clarify your specific problem or add additional details to highlight exactly what you need. As it's currently written, it’s hard to tell exactly what you're asking. See the How to Ask page for help clarifying this question. If this question can be reworded to fit the rules in the help center, please edit the question.

  • What context are you in? Needs more info I think. Are you on that node page and need to get the node ID or something else? – Cottser Dec 1 '15 at 19:50
  • @Cottser I'm on a custom route in a module, the idea is idea is each company have a login page where I can display the company logo and a form login via Resful. – Lhassan Baazzi Dec 1 '15 at 21:15
  • 1
    I don't understand what you are asking and I'm not sure you understand what a slug is? (a slug is a placeholder like {user} or {node} or {anything} and has to be on it's own, e.g. /something/{slug}. I don't see something that could be a slug in your example? What's your route definition? – Berdir Dec 1 '15 at 23:03
  • "Slug" is a word that comes over from WordPress. It is a kind of "machine name" - they are used for url's and HTML attributes like class names, id names - to add to Berdir's comment above. Berdir is right in that one needs to know about routing. Technically speaking, you would need to check how the path maps to the node parameters. But your example seems to indicate this. – James Nov 25 '18 at 14:31

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;
  • 1
    This isn’t necessary, the id is readily available in most contexts. If the question stated where it was trying to be accessed, it might be one or two calls to get it. – Kevin Nov 25 '18 at 10:20
$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]);

Not the answer you're looking for? Browse other questions tagged or ask your own question.