Magento 2 add admin user Programatically

This blogpost has a code to add the admin user programatically, we just need to place the code in a file on our magento root directory.

<?php
// MAGENTO START
include('app\bootstrap.php');

use Magento\Framework\App\Bootstrap;

$bootstrap = Bootstrap::create(BP, $_SERVER);
$objectManager = $bootstrap->getObjectManager();

$appState = $objectManager->get("Magento\Framework\App\State");
$appState->setAreaCode("developer"); /* To set mode as developer */

$userFactory = $objectManager->create('\Magento\User\Model\UserFactory');
$adminInfo = [
    'username'  => 'arushi',
    'firstname' => 'arushi',
    'lastname'    => 'bansal',
    'email'     => 'arushi@w3solver.com',
    'password'  =>'hello@123',       
    'interface_locale' => 'en_US',
    'is_active' => 1
];

$userModel = $userFactory->create();
$userModel->setData($adminInfo);
$userModel->setRoleId(1);
 try{
   $userModel->save(); 
} catch (\Exception $ex) {
    $ex->getMessage();
}


Leave a Comment.