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

\Drupal::currentUser()->id()

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.

<?php
// 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;
?>

Reference

https://drupal.stackexchange.com/questions/184498/how-do-i-get-the-user-id-for-the-currently-logged-in-user