How to display nothing when cover isn't found

Good day everyone,

I have this snippet to fetch the cover image:

<?php if ($cover = $card->images()->findBy("template", "cover")->crop(600, 600)): ?>
<img class="media-cover" src="<?= $cover->url() ?>" alt="<?= $cover->alt()->html() ?>">
<?php endif ?>

When image is there everything is working fine. But sometimes I want to add posts without cover but it breaks the page and Iā€™m getting standard error message. What is the best practice to avoid this? :slight_smile:

The crop must only happen after you have made sure you have an image:

<?php if ($cover = $card->images()->findBy("template", "cover")): ?>
<img class="media-cover" src="<?= $cover->crop(600,600)->url() ?>" alt="<?= $cover->alt()->html() ?>">
<?php endif ?>
1 Like

Great, that helped! :slight_smile: