Calling url() on first() of collection results in error

I have a pages section called steps.

This works:

dump( $tour->steps()->toPages() );
Kirby\Cms\Pages Object
(
    [0] => exhibitions/sammlung-graf/einleitung
    [1] => exhibitions/sammlung-graf/dreschflegel
    [2] => exhibitions/sammlung-graf/manfred-graf
)

This works, too:

foreach ($tour->steps()->toPages() as $step) {
    dump($step->url());
}

Also this works:

dump( $tour->steps()->toPages()->first() );
Kirby\Cms\Page Object
(
    [children] => Kirby\Cms\Pages Object
        (
        )
        ...

But this throws an error:

dump( $tour->steps()->toPages()->first()->url() );
Call to a member function url() on null

I don’t get it?! What am I missing?

Not sure why this happens, but you should never do it like that but always check for an object first:

if ($p = $tour->steps()->toPages()->first()) {
  dump($p);
}

If you are on PHP 8.x, you can also use the null safe operator:

dump( $tour->steps()->toPages()->first()?->url() );

ok, thanks. That helped :slight_smile:
Still, while this works:

$tour->steps()->toPages()->first()?->url()

I would really like to understand why?!
This is not null:

$tour->steps()->toPages()->first()

If someone could educate me, thta would make me happy :nerd_face:

Which Kirby and PHP versions are you using? I can’t reproduce your error (tested with 3.6.3 and PHP 8.0.16).

Kirby 3.6.2
tried PHP 8.0.8 and php 7.4.21
running on MAMP