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 ?
Please use following code to get the current user object in Drupal 8: $user = \Drupal::currentUser();
$user = \Drupal::currentUser();
To get the current userID you can use :
$user = User::load(\Drupal::currentUser()->id());
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 :
\Drupal::currentUser()
returns an AccountProxyInterface
.\Drupal\user\Entity\User::load()
actually returns a user entity object.