May 28, 2019 in Drupal 8, Snippets

How do you get the base url of a drupal 8 website programmatically?

Depending on your current environment, you can use on of the following:

$host = \Drupal::request()->getSchemeAndHttpHost();

Or

$host = \Drupal::request()->getHost();

Or you could use below. This is how core renders the [site:url] token:

$url_options = [
    'absolute' => TRUE,
    'language' => \Drupal::languageManager()->getCurrentLanguage(),
  ];
$site_url = Url::fromRoute('<front>', [], $url_options)->toString();