3

I am automatically creating users in a service, is there a way to check if user exists?

I want to log in id user exist or save a new user if it doesn't, I have the following so far which will add a user:

public function add($user)
{
    craft()->users->saveUser($user);

    $user = craft()->users->getUserByUsernameOrEmail($username);
    craft()->userSession->loginByUserId($user->attributes['id']);   
}
  • Well, craft()->users->getUserByUsernameOrEmail() will return NULL if no users match the username or email address given – can't you just do a call to that method and check the return value before attempting to create a new user? – Mats Mikkel Rummelhoff Feb 26 '15 at 14:05
6

Something like this should work:

public function add($user)
{
    $existingUser = craft()->users->getUserByUsernameOrEmail($user->username);

    if ($existingUser)
    {
        // They exist... log them in.
        craft()->userSession->loginByUserId($existingUser->id);  
    }
    else
    {
        // They don't exist... create them.
        craft()->users->saveUser($user);
    }
}
  • 2
    Except that you just redefined what 'user' is, and thus will be saving 'undefined' — I changed it to '$existingUser'. – Douglas McDonald Feb 26 '15 at 17:39
  • That's what I get for answering before coffee. – Brad Bell Feb 26 '15 at 18:09

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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