1

I'd like to get the following URLs in Drupal 8:

  • /user/register
  • /user/login
  • /logout
  • /user

I already know I can use \Drupal::service('path.current')->getPath() to get the current path. I want to build links to redirect users.

How do I get these paths programatically?

1 Answer 1

2

The user URLs (or routes to be more "Drupal correct") are defined by the core user module (core/modules/user/user.routing.yml)

E.g.

user.register:
  path: '/user/register'
  ...

user.login:
  path: '/user/login'
  ...

user.logout:
  path: '/user/logout'
  ...

user.page:
  path: '/user'
  ...

So you can programmatically build links to these routes like so:

<?php

use Drupal\Core\Link;

// Replace user.login with other routes such as user.page
$user_login_link = Link::createFromRoute(
  t('User log in link'), // The link text
  'user.login', // The link URL generated from the route
);
2
  • 1
    Perfect, thank you! I'll still have to do $user_login_link->getUrl(); if I want only the URL, without the markup tho. Commented Sep 7, 2020 at 18:30
  • I haven't tried this yet, but it appears you can also use Url::fromRoute() api.drupal.org/comment/61929#comment-61929 Commented Sep 10, 2020 at 17:08

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.