Call to a member function crop() on null

I got the error why try to output the thumbnails. Here is my code

 <?php
	        $items = $page->children()->listed()->paginate(12);

		//output image
	        foreach ($items as $item):
	        	$thumb = $item->thumbnail();	
	        	if($item->thumbnail()->isNotEmpty()){
	        		$thumb = $item->thumbnail()->toFile();
	   			}
	   			else{
	   				$thumb = $item->image();
	   			}
	         ?>

	        	<a href="<?= $item->url() ?>">
	        		<img class="product-thumb" 
	        		 src="<?= $thumb->crop(400,400)->url() ?> "  alt="<?= $item->title() ?>" />
	        	</a>
<?php endforeach ?>

The error appears when I made some changes in the blueprint and uploaded some files in the panel. It worked fine before.

Thanks

You are not checking if your $thumb is actually an object:

 <?php
 $items = $page->children()->listed()->paginate(12);

//output image
foreach ($items as $item):
  $thumb = $item->thumbnail()->toFile() ?? $item->image();
?>
    <?php if ($thumb): ?>
        <a href="<?= $item->url() ?>">
            <img class="product-thumb" 
        src="<?= $thumb->crop(400,400)->url() ?> "  alt="<?= $item->title() ?>" />
        </a>
    <?php endif ?>
<?php endforeach ?>

Thanks so much. It works fine now!

Hi,
actually I stumbled over the same mistake but why is it necessary to check for an object?
If it is a object it should also work without the check but it doesn’t?
@texnixe please can you explain it to me why the check is necessary?

If you store an image in a files field and then try to convert the value that is stored in the content to a file object, this will return null if the image was removed/renamed in the meantime.

However, you can only call a file class method like crop()on an object of that class (not on null, a string, an object of another class etc.)

In PHP 8 we will be able to use the nullsafe operator shortcut instead of the if condition:

 $item->thumbnail()->toFile()?->url()