yii2yii2-user

Yii2-user: How to create admin user in batch mode?


When deploying my application there is of course always an admin user.

How can I create such an admin user as a first user without any interaction ...


Solution

  • Found it. There is an easy way to do this with Yii2 builtin migrations.

    In Yii2-user there are some hooks we can use to create users.

    This code has to be inserted in a migration. after creating a new migration ./yii migrate/create, preferably after creating initial tables in the database:

    use yii\db\Transaction;
    use app\models\user\User;
    
    public function safeUp()
    {
        $transaction = $this->getDb()->beginTransaction();
        $user = \Yii::createObject([
            'class'    => User::className(),
            'scenario' => 'create',
            'email'    => 'admin',
            'username' => 'admin@example.com',
            'password' => 'mysecret',
        ]);
        if (!$user->insert(false)) {
            $transaction->rollBack();
            return false;
        }
        $user->confirm();
        $transaction->commit();
    }
    

    The skeleton code can be found in ./migrations/....

    Don't forget to add database config parameters in ./config/db.php and the user module in ./config/console.php