Redirect a parent page to first child page

Hi,
I have a website with two parent pages that each have several child pages. In the main navigation of the site I only list the parent pages, and I want these links to go to the first child page.

I did this on a site a few years back (version 3.5) and used this method:

<?php foreach ( $site->children()->listed() as $parent ) :  ?>
    <a <?php e($parent->isOpen(), 'class="active"'); ?> href="<?= $parent->children()->first()->url() ?>"><?= $parent->title(); ?></a>
<?php endforeach; ?>

But now, on Kirby 4, I get an error saying Call to a member function url() on null. If I var_dump $parent->children()->first() I can see the url bit, so how do I access the value of that?

Thanks in advance.

This kind of error always happens if you don’t check for an object first, before calling a member method

<?php foreach ( $site->children()->listed() as $parent ) :  ?>
    <a <?php e($parent->isOpen(), 'class="active"'); ?> href="<?= $parent->hasChildren() ? $parent->children()->first()->url() : $parent->url() ?>"><?= $parent->title(); ?></a>
<?php endforeach; ?>

Aah, of course. I was only looking at the pages with children and forgetting that one of them doesn’t have any.
Thank you, all working now.