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

Your Answer

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

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