How to loop through referenced entities?

How to loop through referenced entities?

Let's say that your Basic page content type has two referenced fields. One is Entity reference to Articles and one is Entity reference revisions to a Paragraph type called Vote.

How would you loop through the first field and get all Article titles? Or how would you loop through the second field and get all votes? It's very easy. Both Entity reference and Entity reference revisions fields have referencedEntities() method that doesn't exist in the FieldItemList class, that both of these fields extend.

You can get Article titles like this:

$article_titles = [];
$basic_page = Drupal\node\Entity\Node::load($your_node_id);
/** @var \Drupal\Core\Field\EntityReferenceFieldItemList $articles */
$articles = $basic_page->get('field_articles');
/** @var \Drupal\node\Entity\Node $article */
foreach ($articles->referencedEntities() as $article) {
  $article_titles[] = $article->getTitle();

In the same way you can get all Paragraphs:

$total_votes = 0;

$basic_page = Drupal\node\Entity\Node::load($your_node_id);

/** @var \Drupal\entity_reference_revisions\EntityReferenceRevisionsFieldItemList $votes */
$votes = $basic_page->get('field_votes');

/** @var \Drupal\paragraphs\Entity\Paragraph $vote */
foreach ($votes->referencedEntities() as $vote) {
  $total_votes += $vote->field_vote->value;

Method referencedEntities() is doing all the hard work for you, so that you don't have to first get entity target ids and then load each entity. You can see what this method does here:

About the author

Goran Nikolovski is a highly experienced Drupal developer with an extensive skill set that includes PHP, MySQL, HTML, CSS and Javascript. He has experience with large Drupal sites and Drupal Commerce 2.x integration, and he is author of several Drupal modules.