An easy way to store user data in Drupal 8

Kevin howbrook
Nov 8, 2017 · 2 min read

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('user.data');
$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!

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade

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