JoSch
August 31, 2020, 5:28pm
1
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.
Use an if statement to check first.
JoSch
August 31, 2020, 5:41pm
3
Thanks. I feel stupid now.
JoSch:
I feel stupid now.
No reason to feel stupid. It won’t happen to you again…
1 Like