8.3.x Drupal.php public static Drupal::currentUser()
8.0.x Drupal.php public static Drupal::currentUser()
8.1.x Drupal.php public static Drupal::currentUser()
8.2.x Drupal.php public static Drupal::currentUser()
8.4.x Drupal.php public static Drupal::currentUser()

Gets the current active user.

Return value

\Drupal\Core\Session\AccountProxyInterface

160 calls to Drupal::currentUser()
AccessTest::testCreateAccess in core/modules/file/tests/src/Kernel/AccessTest.php
Tests create access checks.
AccessTest::testOnlyOwnerCanDeleteUpdateFile in core/modules/file/tests/src/Kernel/AccessTest.php
Tests that only the file owner can delete or update a file.
AccessTest::testStatusFieldIsNotEditable in core/modules/file/tests/src/Kernel/AccessTest.php
Tests that the status field is not editable.
AssertPageCacheContextsAndTagsTrait::assertCacheTags in core/modules/system/src/Tests/Cache/AssertPageCacheContextsAndTagsTrait.php
Ensures that some cache tags are present in the current response.
authorize_access_allowed in core/authorize.php
Determines if the current user is allowed to run authorize.php.

... See full list

File

core/lib/Drupal.php, line 246
Contains \Drupal.

Class

Drupal
Static Service Container wrapper.

Code

public static function currentUser() {
  return static::getContainer()->get('current_user');
}

Comments

taggartj’s picture

$uid = \Drupal::currentUser()->id();

TristanTheKnightAway’s picture

This worked for me and temporarily stopped my madness.

pownraj’s picture

To access the user object in twig, just use

{% user.id %}

Like mentioned in the docs for nodes, user variable also available but with few restrictions.

Only method names starting with "get", "has", or "is" and a few common
 *   methods such as "id", "label", and "bundle" are available.
jmsosso’s picture

If you want to get the current user from a controller use dependency injection:

class MyController extends ControllerBase {

  /**
   * Drupal\Core\Session\AccountProxy definition.
   *
   * @var \Drupal\Core\Session\AccountProxy
   */
  protected $currentUser;

  /**
   * {@inheritdoc}
   */
  public function __construct(AccountProxy $current_user) {
    $this->currentUser = $current_user;
  }

  /**
   * {@inheritdoc}
   */
  public static function create(ContainerInterface $container) {
    return new static(
      $container->get('current_user')
    );
  }

[...]
Rob230’s picture

FYI you don't need to do this because $currentUser is already injected into ControllerBase (although it's protected, you have to use the method: https://api.drupal.org/api/drupal/core%21lib%21Drupal%21Core%21Controlle...

However, this is useful advice for anyone needing to inject $currentUser into a class that doesn't extend from ControllerBase.