Drupal - How to get instance of referenced entity?

The path to referenced entity is very long:

// $id = some node ID
// $field = field name for entity reference field
$node = Node::load($id);

/** @var \Drupal\Core\Field\Plugin\Field\FieldType\EntityReferenceItem $referenceItem */
$referenceItem = $node->get($field)->first();

/** @var \Drupal\Core\Entity\Plugin\DataType\EntityReference $entityReference */
$entityReference = $referenceItem->get('entity');

/** @var \Drupal\Core\Entity\Plugin\DataType\EntityAdapter $entityAdapter */
$entityAdapter = $entityReference->getTarget();

/** @var \Drupal\Core\Entity\EntityInterface $referencedEntity */
$referencedEntity = $entityAdapter->getValue();

// At this point $referencedEntity is the referenced entity object.

Of course one can still get it via one liner call, but still, it is cumbersome and I wonder why EntityReferenceItem does not provide method that would return the reference entity object.

$referencedEntity = $node
  ->get($field)
  ->first()
  ->get('entity')
  ->getTarget()
  ->getValue()
;

Note: if you have php 8, you can use the nullsafe operator:

$referencedEntity = $node
  ?->get($field)
  ?->first()
  ?->get('entity')
  ?->getTarget()
  ?->getValue()
;

It's also worth noting that it's quite easy to get array of all referenced entities:

$node->get($field)->referencedEntities();

It works because for entity reference fields $node->get($field) returns instance of EntityReferenceFieldItemList which implements referencedEntities() method.


You can use:

$node->field_image->entity

if you want the first value


For how to get an entity from a referenced field. Im agree with @SiliconMind about referencedEntities it return an array of entity objects keyed by field item deltas.

Just simple:

$node->get('field_name')->referencedEntities();

EntityReferenceFieldItemList::referencedEntities

Tags:

Entities

8