How to get the node id the comment is attached to in hook_comment_insert? 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-&gt;bundle() == 'comment_custom' &amp;&amp; $entity-&gt;get('entity_type')-&gt;value == 'node') {

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

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

  }
}
the correct way to load nid is,

$entity-&gt;get('entity_id')-&gt;target_id

and not

$entity-&gt;get('entity_id')-&gt;value

In case of doubt which key to use,

try,

$entity-&gt;get('entity_id')-&gt;getValue()

and inspect the returned value.