How to Get a Node by Its NID in Modern Drupal

Client
  • Omitsis
Technologies
Services
Date
  • 14/06/2024

If you’re coming from Drupal 7, you’ll remember how simple it was to load a node:

$nid = 123;
$node = node_load($nid);

In modern Drupal (8, 9, 10, 11 and beyond) things have changed. We have several ways to do it, each with its own advantages.

The quick way (similar to Drupal 7)

If you’re looking for something similar to what you used to do:

use Drupal\node\Entity\Node;

$nid = 123;
$node = Node::load($nid);

This is the most concise option and perfectly valid for scripts, hooks or quick code.

The recommended way (dependency injection)

In services, controllers or plugins, the proper approach is to inject the EntityTypeManager:

use Drupal\Core\Entity\EntityTypeManagerInterface;
use Drupal\node\NodeInterface;

class MyService {

  public function __construct(
    protected EntityTypeManagerInterface $entityTypeManager,
  ) {}

  public function loadNode(int $nid): ?NodeInterface {
    return $this->entityTypeManager->getStorage('node')->load($nid);
  }

}

Why? Because it makes the code testable, decoupled and follows Drupal standards.

Loading multiple nodes

To load several nodes at once, use loadMultiple():

use Drupal\node\Entity\Node;

$nids = [1, 2, 3, 45, 67];
$nodes = Node::loadMultiple($nids);

foreach ($nodes as $node) {
  // Work with each node
}

Finding nodes by field (EntityQuery)

If you need to search for nodes by some criteria before loading them:

$nids = \Drupal::entityQuery('node')
  ->condition('type', 'article')
  ->condition('status', 1)
  ->condition('field_category', 'technology')
  ->accessCheck(TRUE)
  ->execute();

$nodes = Node::loadMultiple($nids);

Important: Since Drupal 9.2, accessCheck() is mandatory. If you don’t include it, you’ll see a deprecation notice.

Quick reference

SituationRecommended method
Quick script or hookNode::load($nid)
Service or controllerInject EntityTypeManager
Load multiple nodesNode::loadMultiple($nids)
Search by criteriaentityQuery() + loadMultiple()

Bonus: accessing node fields

Once the node is loaded:

// Get the title
$title = $node->getTitle();

// Get a field value
$value = $node->get('field_my_field')->value;

// Get entity reference (e.g.: image, term)
$media = $node->get('field_image')->entity;

// Check if field has a value
if (!$node->get('field_my_field')->isEmpty()) {
  // ...
}
The code has changed compared to Drupal 7, but once you get used to it, the entity system is much more powerful and consistent.

CA

Carlos Rincón

developer

Recent Posts

Plug&Team: when technology stops being a project and becomes part of your team

Plug&Team is Omitsis’ model for integrating into enterprise teams as a true extension of the organization. Moving beyond project-based delivery, we provide continuous technological excellence, sound engineering judgment, and long-term accountability to ensure reliable execution and better strategic decisions.