Get the full/absolute URL of a page in Drupal 10 using the Url class. This snippet covers how to get the URL of the current page, a specific route, or an external website, and how to convert the URL object to a string representation of the absolute URL.
The Url::fromRoute() method is used to get the URL of a specific route, while the Url::fromUri() method is used to get the URL of an external website. The keyword is used to get the URL of the current page.
The toString() method is used to convert the URL object to a string representation of the absolute URL.
Source code viewer
use Drupal\Core\Url; // Get the current page URL. $current_url = Url::fromRoute('<current>'); // Get the URL of a specific route. $route_url = Url::fromRoute('route_name'); // Get the URL of an external website. $external_url = Url::fromUri('https://www.example.com'); // Get the absolute URL. $current_url_absolute = $current_url->toString(); $route_url_absolute = $route_url->toString(); $external_url_absolute = $external_url->toString();Programming Language: PHP