Unable to display image (Call to a member function url() on null)

While:

 <?php foreach($pages->find('menu')->children() as $menu): ?>
     <?php echo $menu->title()->html() ?>
 <?php endforeach ?>

outputs the correct title, the following code:

 <?php foreach($pages->find('menu')->children() as $menu): ?>
     <img src="<?php echo $menu->image()->url() ?>" alt="" class=""/>
 <?php endforeach ?>

results in an error (Call to a member function url() on null).

What do I missing?
The image is located in:

  content/
  content/menu
  content/menu/1-restauant
  content/menu/1-restauant/vegetables.jpg

Do all children have an image in it?

To avoid errors, you should always (always, always, always) check if an image object exists before calling a method on it:

<?php foreach($pages->find('menu')->children() as $menu): ?>
  <?php if($image = $menu->image()): ?>
     <img src="<?php echo $image->url() ?>" alt="" class=""/>
  <?php endif ?>
<?php endforeach ?>
1 Like

Good point!

Thanks, it works now :slight_smile: