Call to a member function url() on null

I can’t work out what is going wrong here and I get an error when trying to use

<?php if ($selected->url()->isNotEmpty()): ?>

My code

<?php $projects = $page->projects()->toStructure(); ?>
<?php foreach($projects as $project): ?>
<?php $selected = $project->project()->toPage(); ?>

    <a href="<?= $selected->url() ?>">
        // Stuff here
    </a>

<?php endforeach ?>

Blueprint:

projects:
    label: Featured Projects
    type: structure
    width: 1/2
    fields:
      project: 
        type: pages
        layout: list
        options: query
        query: site.find('projects').children.listed
        max: 1

In this line you assume the $project->project()->toPage() return a page object. But you cannot rely on that and have to make sure you have one before you call the url() method:

<?php if ( $selected = $project->project()->toPage() ) : ?>
  <a href="<?= $selected->url() ?>">
        // Stuff here
  </a>
<?php endif; ?>

Suggested reading: A brief intro to object oriented programming in PHP | Kirby CMS

1 Like

much appreciated!