I’m trying to get all images of a page, shuffle them and then output the URL of the first image of this shuffled collection.
Why is this throwing an error?
<?php $imgs = $page->images()->shuffle(); $previewImg = $imgs->first() ?> <img src="<?= $previewImg->url() ?>">
(The error thrown is »Call to a member function url() on null«)
If $previewImg = $imgs->first() doesn’t return an image, your call to url will fail with this error. Never call a class method without making sure you have an instance of that class.
$previewImg = $imgs->first()
Use an if statement to check first.
Thanks. I feel stupid now.
No reason to feel stupid. It won’t happen to you again…