How to get the current user object in Drupal 8?

15,761

Solution 1

Please use following code to get the current user object in Drupal 8: $user = \Drupal::currentUser();

Solution 2

One liner way to get a full drupal user object for the current active user :

$account = \Drupal\user\Entity\User::load(\Drupal::currentUser()->id());

Why not just Drupal::currentUser() ? Because most of the time it won't be sufficient as you'll need a fully loaded user object while it's not :

Solution 3

$user = \Drupal::currentUser();

To get the current userID you can use :

$user = User::load(\Drupal::currentUser()->id());

Solution 4

According to entity api, we should not use User::load. Instead, use entityTypeManager like so :

$user_id = \Drupal::currentUser()->id();
$user_entity = \Drupal::entityTypeManager()->getStorage('user')->load($user_id);
Share:
15,761
Vikas Pandey
Author by

Vikas Pandey

Updated on June 04, 2022

Comments

  • Vikas Pandey
    Vikas Pandey almost 2 years

    I am proficient in Drupal 7 where I get the current user object from global $user, but how do I get it in Drupal 8 ?

  • Vikas Pandey
    Vikas Pandey over 6 years
    Thanks Vipin. Is there way to get the user Id directly by using any function or anything global variable.
  • Vipin Mittal
    Vipin Mittal over 6 years
    Yes Vikas. use $ownerId = \Drupal::currentUser()->id();
  • kenS
    kenS over 4 years
    Per the Entity API documentation that you just linked, one should "Avoid using the static Entity::load() method in object oriented code. Instead use dependency injection to inject the entity type manager and load the entity with $this->entityTypeManager->getStorage($entity_type)->load($en‌​tity_id)." It is worth noting that it is fine to use the static Entity::load() method in other circumstances where you wouldn't be using dependency injection, though, such as a .module file etc.
  • kenS
    kenS over 4 years
    Also, the code you shared above does NOT use dependency injection, as recommended by the Entity API, which defeats the purpose of preferring $this->entityTypeManager->getStorage($entity_type)->load($en‌​tity_id) over the static Entity::load() method.
  • JFK
    JFK over 4 years
    Thanks for your contribution @kenS, you're right about that dependency injection. Nevertheless, my answer has the advantage of not having to include 'use Drupal\user\Entity\User;' at the top of your php file.
  • kenS
    kenS over 4 years
    True enough. This answer stackoverflow.com/a/57026412/10146245 likewise does not require a use statement and IMO is easier code to write and to read, so personally that's what I'd prefer when not using dependency injection. But the reason for my downvote is not your code, which looks fine and is a valid way to get the current user, but because your statement above the code ("According to entity api, we should not use User::load. Instead, use entityTypeManager...") is inaccurate/misleading in the manner that I pointed out.