Accessing custom user data in Drupal 8

In Drupal 7, we can read the current user's custom data by:

  
global $user;
$user_obj = user_load($user->uid);
print_r($user_obj->data);
  

... and write by:

  
global $user;
$user_obj = user_load($user->uid);
user_save($user_obj, array('data' => array('key' => $value)));
  

Now in Drupal 8, we can read the current user's custom data by:

  
$user_data = \Drupal::service('user.data')->get('your_module_name', \Drupal::currentUser()->id(), 'key');
print_r($user_data);
  

... and write by:

  
\Drupal::service('user.data')->set('your_module_name', \Drupal::currentUser()->id(), 'key', $value);
  

Comments

Add new comment

Restricted HTML

  • Allowed HTML tags: <a href hreflang> <em> <strong> <cite> <blockquote cite> <code> <ul type> <ol start type> <li> <dl> <dt> <dd> <h2 id> <h3 id> <h4 id> <h5 id> <h6 id>
  • Lines and paragraphs break automatically.