Getting thumbnail results in error (Call to a member function thumb() on null)

Underneath several pages I have a bit that gets random projects:

    <footer class="site-footer" role="contentinfo">

        <?php if ($page->template() == "project" || $page->template() == "article"):
            $featured = $pages->find('projecten')->children()->shuffle()->limit(4); ?>

            <div class="random-content container">
                <a href="/projecten"><h3 class="random-content-title">Meer projecten</h3></a>
                <ul class="collection">
                  <?php foreach($featured as $project): ?>
                  <li class="collection-item project">
                    <a href="<?php echo $project->url() ?>">
                        <img src="<?= $project->images()->sortBy('sort', 'asc')->first()->thumb(array('width' => 300))->url() ?>" alt="Thumbnail for the project <?= $project->title()->html() ?>" class="project-thumbnail" />
                    </a>
                    <h4><?php echo $project->title() ?></h4>
                  </li>
                  <?php endforeach ?>
                </ul>
            </div>

        <?php endif ?>

      …

</footer>

However, sometimes, I get this error: Call to a member function thumb() on null.

Here is the footer and the stack trace. Every project has at least one image, so what could be the reason of the error?

Interestingly, I get thumbnails of 16 random projects on the front page, but this never results in an error.

I don’t know why this is happening, but I recommend not to use code like this but instead always! check if you have an image:

<?php if($image = $project->images()->sortBy('sort', 'asc')->first()); ?>
<a href="<?php echo $project->url() ?>">
  <img src="<?= $image->thumb(array('width' => 300))->url() ?>" alt="Thumbnail for the project <?= $project->title()->html() ?>" class="project-thumbnail" />
</a>
<?php endif ?>

You can never be sure if the image is still there after some time…

Is there a way to do this check before calling the random projects? Because I’d like to only display them if they have an image. (Which all of them do, by the way.)

I wouldn’t remove the check and you can’t put it anywhere else, because without the project you can’t check if it has images.

What you can do, however, is filter your projects:

$featured = $pages->find('projecten')->children()->filterBy('hasImages', true)->shuffle()->limit(4); ?>

This is exactly what I meant, thank you so much!