How can I register and login a user in my Controller? I have tried something like this:

$newUser = new User($userName, $userPassword, $userEmail);
up vote 1 down vote accepted

Put this at the top of the file:

use craft\elements\User;

Within your function use the following code:

$user = new User();
$user->pending = true;
$user->username = $contact["login_email"];
$user->firstName = $contact["first_name"];
$user->lastName = $contact["last_name"];
$user->email = $contact["login_email"];
$user->passwordResetRequired = false;
$user->validate(null, false);
Craft::$app->getElements()->saveElement($user, false);
Craft::$app->users->assignUserToGroups($user->id, [1]);

The sendActivationEmail is not a required step and can be removed but this code is working on a Craft 3 site I've been building and it creates user accounts.

This assumes that a $contacts array has been set with all of the correct values, just swap these out for your own values or omit them if you don't have any. From here you should be able to customise it though for what you need once the user account is created.

The final step for you to log in as that user would be to use something like this, this is untested however and may need some tweaking but has come from the docs:

$userLogin = new \Craft\web\User();
  • Why do you initiate a new instance of the component rather than using the existing one? Do you want to avoid events? – Robin Schambach Nov 8 at 14:14

Your Answer


By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

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