How can I get the node id the comment is attached to in hook_comment_insert?

I tried the following code:

function mymodule_comment_insert(Drupal\Core\Entity\EntityInterface $entity) {
  if ($entity->bundle() == 'comment_custom' && $entity->get('entity_type')->value == 'node') {

    // Below returns empty, because "$entity->get('entity_id')->value" is empty.
    $node = Node::load($entity->get('entity_id')->value);

    // No luck with this one too.
    $node = \Drupal::routeMatch()->getParameter('node');

  • i wanted to pick up the "node" to which the comment is being attached (and react accordingly). – D34dman Jul 14 '16 at 8:07

the correct way to load nid is,


and not


In case of doubt which key to use,



and inspect the returned value.


This is a late answer based on another question flagged as duplicate of this one.

The Comment entity has some helpful methods for getting back the entity it's associated with.

CommentInterface::getCommentedEntity should get the entity object that the comment is attached to.


if ($entity instanceof \Drupal\comment\CommentInterface) {
   $commentedEntity = $entity->getCommentedEntity();
   if ($commentedEntity && $commentedEntity instanceof \Drupal\node\NodeInterface) {
     // The entity that the comment is attached to is a node.
     // Do something with the commented entity.
  • That is the proper answer – Hubert Sep 16 '20 at 20:39

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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