Get image URL easily without errors?

I have a blueprint with field of type files and multiple: false. I use it to specify a single image via the panel.

You normally do that with:

$image = $page->myImage()->toFile()->url();

Problem is, if the image is not specified or empty, you get an error:

Call to a member function url() on null

so you have to specify it like that:

$imageFile = $page->myImage()->toFile();
$imageUrl = $imageFile ? $imageFile->url() : null;

This can get pretty annoying if you have a bunch of fields with a single image. Is there some way to specify it in a single line with a single variable?

Perhaps a new method that returns the URL of the asset specified by the field, and null if it doesn’t exist or the field is empty. Then you’ll be able to do:

<?php if ($page->myImage()->assetUrl()): ?>
   <img src="<?= $page->myImage()->assetUrl() ?>">
<?php endif; ?>

We always recommend to do this in templates:

<?php if ($image = $page->myImage()->toFile()): ?>
   <img src="<?= $image->url() ?>">
<?php endif; ?>
1 Like

Oh, yes, didn’t thought of that trick. Very neat and clever! Thanks!