I want to find out whether a physical file is managed by Drupal and if it is, then load it.

I'm having trouble with the documentation which keeps displaying "File not found" at crucial moments, but it seemed that this ought to work:

$query = \Drupal::entityQuery('file');
$query->condition('uri', $file_uri);
$entity_ids = $query->execute();
if (count($entity_ids) == 1) {
    $file = \Drupal::entityLoad($entity_ids[0]);

However, I get this message:

PHP Fatal error:  Call to undefined method Drupal::entityLoad()

2 Answers 2


There is no such method as \Drupal::entityLoad(). Use the static method on the entity type. Assuming "File", you should use:

$file = \Drupal\file\Entity\File::load(reset($entity_ids));

Berdir pointed out in a comment that QueryInterface::execute() returns an array keyed by entity ID or revision ID so reset() is the thing to use to get the first element.

  • 1
    $entity_ids[0] is wrong, the key is the id/revision id, 0 won't exist. use reset()
    – Berdir
    Commented Nov 20, 2016 at 21:18

To load the entity by ID you can use the following code:

/** @var \Drupal\file\FileInterface|null $file*/
$file = \Drupal::entityTypeManager()

But if you need to load the file entity by the given file URI there is a method called loadByProperties in EntityStorageInterface:

/** @var \Drupal\file\FileInterface[] $files*/
$files = \Drupal::entityTypeManager()
  ->loadByProperties(['uri' => $uri]);
if (!empty($files)) {
  $file = reset($files);

See Load a file entity by URI

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.