Drupal 8 Roles Storage

Submitted by deaconblues on Tue, 11/25/2014 - 00:22

In Drupal 7, you could write a simple SQL query to get access to the Roles table and then consume them programatically as you please.  Drupal 8 is a bit different but it makes sense once you see what's going on in the background.  I had a bit of an issue finding details on this given that D8 is in beta 3 as I write this, so here is what I found.

Drupal 8 has centralized a great deal of the various settings for the application into the single "config" table, including Roles as well.  Here's a small snippet to show how exactly Roles are stored in the table.  The Role ID is part of the Name field while the settings for the Role are serialized into the Data field on the table. 

Drupal 8 Roles DB Screenshot

Luckily, there is some pretty easy API code that you can use to get to everything you need for the Roles in your application.

    $prefix = 'user.role.';
    $cut = strlen($prefix);
    $result = \Drupal::service('config.storage')->listAll($prefix);
    foreach ($result as $role) {
      $rid = substr($role, $cut);
      $config = \Drupal::config("user.role.$rid");
      $role_name = $config->get('label');          

The biggest thing to pay attention to here is that the RID value has changed from a numerical field in D7 to a text field in D8.  So you'll need to be sure to account for this in any modules that pull Roles in the mix.  You'll see this pretty obviously in the "users_roles" table.

Drupal 8 Users_Roles Table

Hope this helps!