Having difficulties creating a new user in a custom controller, here's my implementation:

use craft\records\User;

$user = new User;
$user->firstName = $userData['firstName'];
$user->lastName = $userData['lastName'];
$user->username = $userData['loginName'];
$user->email = $userData['loginName'];
$user->password = $userData['password'];

$response = $user->insert();


SQLSTATE[HY000]: General error: 1364 Field 'id' doesn't have a default value
The SQL being executed was: INSERT INTO `craft_users` (`firstName`, `lastName`, `username`, `email`, `password`, `dateCreated`, `uid`, `dateUpdated`) VALUES ('Tristan', 'Gemus', '[email protected]', '[email protected]', 'password', '2019-03-28 15:53:10', '85468ad6-63cc-499d-baf4-32aaaf55bfb2', '2019-03-28 15:53:10')

The response returns false. Thoughts?

1 Answer 1


Take a look at Craft's own UsersController->actionSaveUser().

You're probably looking for something closer to this:

$user = new craft\elements\User();

$user->firstName = $firstName;
$user->lastName = $lastName;
$user->username = $userName;
$user->email = $email;
$user->password = $password;

if ($user->validate(null, false)) {
    Craft::$app->getElements()->saveElement($user, false);
  • 1
    I've found that if you actually want to set the password, you need to use $user->newPassword = $password; Other than that, this works exactly as expected, thanks.
    – jymbob
    May 14, 2019 at 12:29
  • Thanks for this. What is $user->validate(null, false)?
    – iamkeir
    Mar 22, 2022 at 17:18

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.