Drupal - How do I get the username from the user ID?

You can use user_load or \Drupal\user\Entity\User::load to do this. Below code will provide the solution

 public function content() {
     $account = \Drupal\user\Entity\User::load('uid'); // pass your uid
     $name = $account->getUsername();
     drupal_set_message($name);
 }

$name gives the username of the user.


In D8, if you don't know the uid, you can do this:

function test_user_login(\Drupal\Core\Session\AccountInterface $account) {
   $account = \Drupal\user\Entity\User::load(\Drupal::currentUser()->id());
   $user = $account->get('name')->value;
   drupal_set_message($user, 'status'); }

Tags:

Users

8