Skip to main content

Is Current User is administrator

DrupalVIP Support

Drupal has its hooking mechanism which just got better.

Within this mechanism, I can put another layers of security and check the current user.
in some cases, I don't want to do it per administrators, so now I have a need to test if current user is an administrator

 

$current_user = \Drupal::currentUser();
$roles = $current_user->getRoles();
$isAdmin = in_array('administrator', $roles);

this will return the following:

Array
(
  [0] => authenticated
  [1] => administrator
  [2] => some_other_role
)

 

you can also use drupal service to Determines whether the active route is an admin one.

$is_admin = \Drupal::service('router.admin_context')->isAdminRoute();
if ($is_admin) {
  // Do stuff.
}

https://api.drupal.org/api/drupal/core!lib!Drupal!Core!Routing!AdminContext.php/function/AdminContext%3A%3AisAdminRoute/8.2.x