1

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

$newUser = new User($userName, $userPassword, $userEmail);
Craft::$app->elements->saveUser($newUser);

1 Answer 1

5

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]);
Craft::$app->getUsers()->sendActivationEmail($user);

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();
$userLogin->loginByUserId($user->id);
5
  • Why do you initiate a new instance of the component rather than using the existing one? Do you want to avoid events? Commented Nov 8, 2018 at 14:14
  • Robin, how would you use the existing one? Commented Dec 11, 2018 at 1:40
  • I'm really confused how $user->id is set in your code. The saveElement method is not taking a &$referenced argument so the fact that it updates the ID in the model should mean nothing to the code calling it. What am I missing here? Commented Aug 1, 2019 at 15:48
  • n/m i totally forgot they changed object arguments are passed by reference by default after php5. Commented Aug 1, 2019 at 16:51
  • @DavidAaronMcInnis I believe you should be able to call the Craft::$app->getUser()->login($user) method.
    – Chris
    Commented Aug 24, 2019 at 14:52

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.