yii 2 – creating a new user using migrations

After installing yii framework 2 you will probably face the following problem: “How in the world a default user is created ?” (in order to log in into demo backend).

One way is the following . Seems pretty logical to me too. As you figured out you after you create the database you need to do a migrate in order to have the needed database tables. However this tables are empty.
Let’s fill them with an admin account.

First we need to create a migration:

yii create/migration insert_user

The resulting file is something like this :

This is the placeholder where we can actually add the usefull stuff. So … Without any delays we will add the User model to it and call User::create .
This is how it should look like:

‘admin’,
‘password’ => ‘demodemo’,
’email’ => ‘demo@tfm.ro’
)
);
}

public function down()
{
echo “m140803_224937_insert_user cannot be reverted.\n”;

return true;
}
}

Migrations are a very powerfull tool in yii framework 2. You can alter database with it, you can insert test or live data . And sometime you can revert the modifications.