How to get the logged-in user's id in drupal?

| | 1 min read

In pre Drupal 8 era, the global variable $user was available every where, from you can easily get the current logged in user id. For all new version of Drupal, you should use


Once you have the user id, you can use the User::load to get the user object.

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

Here is an example of retrieving specific information from the user object.

// Load the current user.
$user = User::load(\Drupal::currentUser()->id());

$email = $user->get('mail')->value;
$name = $user->get('name')->value;
$uid= $user->get('uid')->value;