Customizing a user object

Loading the object

// Load the currently logged in user
$user = \Drupal\user\Entity\User::load(\Drupal::currentUser()->id());

// Or load any user:
use Drupal\user\Entity\User;
$user = User::load($uid);

// Procedurally:
$user = user_load($uid);


// The User class inherits the magic setter method __set() from
// parent class ContentEntityBase, enabling you to do:
$user->name = $name;
$user->mail= $mail;

// This works too: 
$user->setEmail ($mail); 

// Or this: 
$user->set('name', $name);

Setting a custom field

$user->set('field_occupation', 'Web developer');

Removing a role

// Role identifier is a string now, e.g. $user->removeRole('editor');

Setting the password


Activating the account


More methods are found here.