Get the url of a page from a pages field

I’m currently using the “pages”-field in the blueprint to select a page to which I would like to link.
But I have no clue how to get the url from the field value.
“$page->fieldname()->url()” does not work. It only shows “- pagename”.
Maybe I understood something completely wrong and there’s a right way to make the user select a page and get the url to it?

For a single page, you can convert the stored field value to a page object using toPage(). Then if the page exists, call the url() method.

if ($related = $page->fieldname()->toPage()) {
  echo $related->url();

Or using a ternary operator:

<?= ($related = $page->fieldname()->toPage()) ? $related->url() : '' ?>

Checking if the object exists is necessary to prevent “Call to a member function xx() on null” errors.

I already tried to convert it with toPage() which didn’t work either. So the error must be located somewhere in my code and yes - as always - it was my fault. I’m using localization with custom slugs and it only works if all pages have a custom slug. Maybe this is a bug and I’ll try to replicate it later, but currently my deadline is running towards me and I got no time for that. :sweat_smile:
Thank you anyways for your help! :pray:

Interesting, would be great to see your blueprint for the related page definition, when you have more time and what is actually stored in the page.

After a few more tests, I think it’s not a bug but simply not the result I expect.
When using the slug field to give the user an option to overwrite/localize the url, I would expect that kirby uses the regular page-id for the url as long as the slug field is empty. But it doesn’t and instead uses the empty slug.
Another “problem” I ran into is the $site->url(). When using localization, it always returns the base-url with the language suffix included. I would expect that function for $language->url() only. For my spedific case I found out, that I can use $kirby->url(‘assets’) to access my stylesheets and javascripts, but as I already said, this is simply counter to expectation.