How to check current user role

By mourad-zitouni, 26 December, 2021

This time we will check if the current user has role 'administrator', we will use a simple controller example to demonstrate that.

First we will define the route for the controller (mymodule.routing.yml):

mymodule.user.check_role:
  path: '/admin/user/checkrole'
  defaults:
    _controller: '\Drupal\image_formatter\Controller\MyController::checkUserRole'
    _title: 'Check user role'
  requirements:
    _permission: 'administer site configuration'

Then we will add the controller class:

<?php

namespace Drupal\mymodule\Controller;

use Drupal\Core\Controller\ControllerBase;
use Drupal\Core\Session\AccountInterface;
use Symfony\Component\DependencyInjection\ContainerInterface;

/**
 * Class MyController
 * @package Drupal\mymodule\Controller
 */
class MyController extends ControllerBase {

  protected $currentUser;

  /**
   * MyService constructor.
   * @param AccountInterface $currentUser
   */
  public function __construct(AccountInterface $currentUser) {
    $this->currentUser = $currentUser;
  }

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


  /**
   * Check current user role
   */
  public function checkUserRole() {
    $user_roles = $this->currentUser->getRoles();
    if (in_array('administrator', $user_roles)) {
      $build = [
        '#markup' => $this->t('The current user has administrator role.')
      ];
    }
    else {
      $build = [
        '#markup' => $this->t('The current user does not have administrator role.')
      ];
    }

    return $build;
  }

}

Here the build contains the markup the controller will display on the page.

Comments