Help understanding error in template—Call to a member function url() on null

I’m using the Kirby Starterkit to develop a new website for our studio. Upon trying to view several blog posts, I am getting an error I don’t understand: Call to a member function url() on null. The error is in the following line, with the <img> tag:

<?php if($item->coverimage()->isNotEmpty()): ?>
  <figure>
    <img src="<?= $item->coverimage()->toFile()->url() ?>" alt="" />
  </figure>
<?php endif ?>

The offending blog post has this as its cover image.

----

Coverimage: 20161011-INTRO-0904.jpg

----

Strangely, viewing the individual blog post works just fine.

How can I debug this?

Does the selected file exist? You only check if the “coverimage” field is not empty. But if the file does not exist (e.g. has been deleted afterwards), toFile() returns null and the url() method is invalid.

1 Like

As @flokosiol said, the file could still not exist. Code that checks that:

 <?php if($img = $item->coverimage()->toFile()): ?>
  <figure>
    <img src="<?= $img->url() ?>" alt="" />
  </figure>
<?php endif ?>
1 Like

Thanks so much @distantnative and @flokosiol! This solved my issue.