Drupal - How do I get the current node ID?

The parameter will have been upcasted from nid to full node object by the time you get access to it, so:

$node = \Drupal::routeMatch()->getParameter('node');
if ($node instanceof \Drupal\node\NodeInterface) {
  // You can get nid and anything else you need from the node object.
  $nid = $node->id();
}

See the change record for more information.


It is correct to use \Drupal::routeMatch()->getParameter('node'). If you just need the node ID, you can use \Drupal::routeMatch()->getRawParameter('node').


if you are using or creating custom block then you have to follow this code to get current url node id.

// add libraries
use Drupal\Core\Cache\Cache;  

// code to get nid

$node = \Drupal::routeMatch()->getParameter('node');
  $node->id()  // get current node id (current url node id)


// for cache

public function getCacheTags() {
  //With this when your node change your block will rebuild
  if ($node = \Drupal::routeMatch()->getParameter('node')) {
  //if there is node add its cachetag
    return Cache::mergeTags(parent::getCacheTags(), array('node:' . $node->id()));
  } else {
    //Return default tags instead.
    return parent::getCacheTags();
  }
}

public function getCacheContexts() {
  //if you depends on \Drupal::routeMatch()
  //you must set context of this block with 'route' context tag.
  //Every new route this block will rebuild
  return Cache::mergeContexts(parent::getCacheContexts(), array('route'));
}

Tags:

Nodes

8