Safe and elegant way to access nested entities via fields
Suggestion, create a domain object that has the logic.

Normally these entities represent something that fits your business-domain.

E.g in your instance, the node might be an event.

So you might model a domain object called EventWrapper.

&lt;?php

namespace Drupal\my_domain;
use Drupal\node\NodeInterface;
use Drupal\media\MediaInterface;
use Drupal\file\FileInterface;

class EventWrapper {
  protected $node;
  public static function fromNode(NodeInterface $node): EventWrapper {
    $instance = new static();
    $instance-&gt;node = $node;
    return $instance;
  }
  public function getMedia() : ?MediaInterface {
    if ($this-&gt;node-&gt;hasField('field_media') &amp;&amp; !$this-&gt;node-&gt;get('field_media')-&gt;isEmpty()) {
      return $this-&gt;node-&gt;field_media-&gt;entity;
    }
    return NULL;
  }
  public function getMediaImage() : ?FileInterface {
    if (($media = this-&gt;getMedia()) &amp;&amp; $media-&gt;hasField('field_file') &amp;&amp; !$media-&gt;get('field_file')-&gt;isEmpty()) {
      return $media-&gt;field_file-&gt;entity;
    }
    return NULL;
  }
  public function getImageCaption(): ?string {
    if (($file = this-&gt;getMediaImage()) &amp;&amp; $file-&gt;hasField('field_text') &amp;&amp; !$file-&gt;get('field_text')-&gt;isEmpty()) {
      return $file-&gt;field_text-&gt;value;
    }
    return NULL;
  }
}


Then in your code:

&lt;?php

$image_caption = EventWrapper::fromNode($node)-&gt;getImageCaption();