User Login


After looking through basic app template I got a question.

Any particular reason why User::findByUsername($this->username) is called twice during login?

(first time at validatePassword(), second time after validation right before Yii::$app->user->login(); )

Why can’t we do just

public function rules()


    return [

        // username and password are both required

        [['username', 'password'], 'required'],

        // rememberMe must be a boolean value

        ['rememberMe', 'boolean'],



public function login()


    if ($this->validate()) {

        $user = User::findByUsername($this->username);

        if ($user && $user->validatePassword($this->password)) {

            return Yii::$app->user->login($user, $this->rememberMe ? 3600*24*30 : 0);

        } else {

            $this->addError('password', 'Incorrect username or password.');



    return false;



Btw I suppose this

Yii::$app->user->login($user, $this->rememberMe ? 3600*24*30 : 0);

return true;

must look like this

return Yii::$app->user->login($user, $this->rememberMe ? 3600*24*30 : 0);

because technically login() can return false.

Александр Макаров - как Сталин.

Ты ему слово - он тебе ссылку :D

PS. Sorry for russian, it’s untranslatable. :)

Lol ;D

Btw, what’s that for?

Looks like support for different logins during one request. Any usecase?

Well, it’s just a local cache not to make request twice. Previous solution wasn’t logically correct.

This solution is also not logically correct. LoginForm will always have only one user, so why make a users array? What qiang meant was to write it like this:

        private $_user;


         * Finds user


         * @return User|null


        private function getUser()


                if ($this->_user === null) {

                        $this->_user = User::findByUsername($this->username);


                return $this->_user;


Yeah. He already fixed it.