I have a link field, which I can populate with both internal and external links:


I'm building an API that parses the node and returns the URL from the link field:


Which returns internal:/node/123 which makes this URL useless.

If I try using use Drupal\Core\Url; and Url::fromUri($node->my_field->uri), I get a 500 error!

So what is the correct approach for getting a formatted URL, that can parse both internal and external links?

1 Answer 1


just kidding. To help future devs with this issue, check the logs *duh and you'll see this:

PHP message: Uncaught PHP Exception InvalidArgumentException: "The URI '' is invalid.

So, check for the uri value first!

$node->my_field->uri ? Url::fromUri($node->my_field->uri)->toString() : null,

  • 1
    You can also use $node->get('my_field')->get(0)->getUrl(). you still need to check it for not being empty though
    – Berdir
    Feb 19, 2018 at 20:36

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.