How to Load Node, File, Taxonomy Entities by ID in Drupal 8?

| | 1 min read

To load node details using its id in Drupal 8 uses the following syntax:

$node_details = Node::load($nid);

We can load multiple nodes in Drupal 8 using load multiple() function. Note that the parameter should be an array of ids.

$nodes = Node::loadMultiple($nids);
foreach ($nodes as $node_content) {
  $title = $node_content->getTitle();
  $created_by = $node_content->getOwner();
  $type = $node_content->getType();
  $field1 = $node_content->field_FIELD_NAME->value;
  // Get necessary fileds like this.

If it is a node page, then we can get

$node_content = \Drupal::routeMatch()->getParameter('node');. Similarly we can load file by id and get its contents like this:

$file = File::load($file_fid);
$file_url = $file->url();
$file_name = $file->getFilename();
$url = Url::fromUri($file_url);
$file_user_entity = $file->getOwner()
$file_user_id = $file->getOwnerId()
$size = $file->getSize();
// Getting all other details of the file goes here.

We can load multiple files like node using File::loadMultiple($fids).

For taxonomy term loading we have to pass its target id Term::load($keyword_name->target_id);. We can use getName(), getVocabularyId(), getDescription() etc.

For vocabularies we can use, Vocabulary::load($vid). If there is an object for vocabulary then we can get the vocabulary hierarchy by using $vb_obj->getHierarchy(). Note that we have to use the entity class for appropriate load use Drupal\node\Entity\ENTITY_NAME;. For example:

use Drupal\node\Entity\Node;
use Drupal\taxonomy\Entity\Term;
use Drupal\file\Entity\File;

Hope this helps.