An easy way to store user data in Drupal 8

Back in the day, drupal 7 had quite a useful way of stashing (occasionally arbitrary) values in the database. Remember…

variable_set($name, $value)
variable_get($name, $value)

In Drupal 8, these functions have been replaced with ‘the new configuration system API/storage’. You can read about that here. But, there is more…

There is a nice way to set and get user data in drupal 8. We can make use of the users_data table. Take a look, it’s more than likely empty. Here is the set method:

$userData = \Drupal::service('');
$userData->set('my_module', $uid, 'a_key', 'Here is a value');
What the users_data table looks like in the drupal database

And to get the data:

$data = $userData->get('my_module', $uid, 'a_key');
Kint of the user data example

It’s still definitely worth learning about the new configuration system API for Drupal 8, but this is nice one to keep in the toolbox!

Developer, I also make art and listen to techno

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store