How do I get the global user object in hook_preprocess_page()?

1 Answer 1

public function behave() {
  $account = \Drupal::currentUser();
  if ($account->id() == 1) {
    return "Hi, boss!";
  else {
    return "You are not the site administrator.";

Note that in neither case is the value an actual User object. Rather, as of Drupal 8 it is a UserSession object, which duplicates some, but not all, of the information of a user. It may also represent the Anonymous User rather than a saved User entity. See link for more information.

  • only two lines are sufficient $account = \Drupal::currentUser(); $account->id() Commented Dec 1, 2015 at 8:49
  • 1
    @KamalOberoi sure but the code is a much better example than just having those two lines IMO.
    – star-szr
    Commented Dec 1, 2015 at 20:47
  • $account->id() is returning string not integer so if you want to compare with an integer value you should us if ((int) $account->id() == 1) Commented Apr 27, 2018 at 19:15

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.