Login user with database in yii 2 framework

Login user with database in yii 2 framework
Reading Time: 3 minutes

In Yii 2, the login form is implemented in basic theme by default. But the main problem is login is not associated with any tables. It is done by a user array. We will implement it by user table.

Steps to login user with database

  1. In this example, what we will do is we will create user table. In user, table you must have username and password field. Store password in md5 which is more secure. In this example, I have used md5. Now when the user enters the password, Convert the string to md5 and match with the database password. Below is my user table.
  2. Now let’s try to understand everything steps by step. When the user enters username and password then our site controller login action is called.

    In this action, loginForm model is used. If we open, this model there are some rules is defined. First rules will be validated. let’s see which rules are applied.

    In this, username and password are required. you can change according to your needs. For password field, we have called validatePassword rule which is defined below in this model.

    This function will take the password and if there is no error then it will return the user info. To validate password it will call $user->validatePassword($this->password) . In the user model, we have the validatePassword function. see below

    I have used md5 here because, in the database, I have stored the password in md5 format. If the password will be equal then $model->login() which is called in login action of  site controller . below is the login action of loginForm model.

    $this->getUser() will call the getUser action which is defined below.

    In this, we have used User::findByUsername($this->username) . It will call findByUsername function of the user model. we have passed username because I am using username field to log in. you can use email field also. For this, you have to call custom function and define according to your need.

    This function will find the user record from the user table. Also, you have to do one thing very important. Comment the virtual fields and user array which is written in this User model. Do like this below.

    One more thing, extend the active record to this class if it is not done earlier.

    This is all you have to do. If you face any issue please mention below in comments.

One Comment on “Login user with database in yii 2 framework”

Leave a Reply

Your email address will not be published. Required fields are marked *