Skip to main content

Drupal 8^ Current User Object, useful methods and what they return

Getting current user object is very useful. These are the most common methods of the Drupal User Object.

get current user in drupal 8

$current_user = \Drupal::currentUser();

$uid = $current_user->id();
It returns user id of current user.

$user_mail = $current_user->getEmail();
It returns user email id.

$user_display_name = $current_user->getDisplayName();
It returns user display name.

$user_account_name = $current_user->getAccountName()
It returns user account name.

$user_roles = $current_user->getRoles();
It returns array of current user has.

$current_user->isAnonymous();
It returns true or false.

$current_user->isAuthenticated();
It returns true or false.

$current_user->getLastAccessedTime();
It returns timestamp of last logged in time for this user

from: https://gist.github.com/radheymkumar/4093d0158ba3642a08e662965555866a

php oop