Using ->url() on an image from another page not working

Hi there, I’m currently trying to call an image url from a subpage onto the homepage using the following code.

          <div <?php echo 'id="collapse'.$k.'"' ?> class="panel-collapse collapse" role="tabpanel" <?php echo 'aria-labelledby="heading'.$k.'"' ?>>
            <div class="panel-body">
            <?php foreach ($item->children() as $subitem): 
              $image = $subitem->preview()->toFiles();
              ?>
              <a class="sub-item" href="<?= $subitem->url() ?>">
              <?= $subitem->title()->kt() ?></a>
              <img src="<?= $subitem->preview()->url() ?>">
            <?php endforeach ?>
            </div>
          </div>
        </div> 

However doing so only outputs the file name as “—6.jpg” adding in a dash. How can I get this to work properly? and using $image->url() outputs nothing.

In this line you convert your preview field content into a files object (so on the right track) but then you are not using it but just calling the field content. Also, I assume you only have a single image, not multiple, so using toFile() is more suitable than toFiles().

<?php foreach ($item->children() as $subitem): 
 <?php $image = $subitem->preview()->toFile(); ?>

 <a class="sub-item" href="<?= $subitem->url() ?>">
    <?= $subitem->title()->kt() ?></a>
    <?php if ($image): ?>
        <img src="<?= $image->url() ?>">
    <?php endif ?>
<?php endforeach ?>