Drupal - Access user fields?
\Drupal::currentUser()
returns an Drupal\Core\Session\AccountInterface
object. That could be a full user (that would be a Drupal\user\UserInterface
), but right now, for the default authentication method, it is not.
Use this to get the user entity and all the fields:
$user = \Drupal\user\Entity\User::load(\Drupal::currentUser()->id())
D7 had exactly the same behavior, the difference now is just that in D7, they were simply different stdClass'es, now you have explicit interfaces to differentiate the two.
And here is how to get it out of that object:
// Load the current user.
$user = \Drupal\user\Entity\User::load(\Drupal::currentUser()->id());
// Get field data from that user.
$website = $user->get('field_website')->value;
$body = $user->get('body')->value;
// Some default getters include.
$email = $user->get('mail')->value;
$name = $user->get('name')->value;
$uid= $user->get('uid')->value;