Programmatically Create New Admin User in Magento 2

Here we will see how to create new admin user programmatically in Magento 2. By default in Magento 2, we can create an admin user easily on the backend and also by using CLI command. You can find the following blog links for those features,

Those features will be helpful when you want to create a single admin user at a time. But in some cases (i.e, migrating data from another environment to Magento 2) if you want to create the bulk of admin users, You have to create a custom script to add a bulk of admin users in Magento 2. Thus here is the blog which will help you to develop a custom script to add a bulk of admin users in Magento 2.

First create a new php file (i.e, add_admin_user.php) in your Magento 2 root folder and add the following code to create new admin user,

use Magento\Framework\App\Bootstrap;
 * If the external file is in the root folder
require __DIR__ . '/app/bootstrap.php';
$params = $_SERVER;
$bootstrap = Bootstrap::create(BP, $params);
$obj = $bootstrap->getObjectManager();

$userInfo = [];

$userInfo['role_id']  = 1;
$userInfo['username'] = 'admin';
$userInfo['firstname'] = 'BlogTreat';
$userInfo['lastname'] = 'Admin';
$userInfo['email'] = '';
$userInfo['password'] = 'admin@123';
$userInfo['interface_locale'] = 'en_US';
$userInfo['is_active'] = '1';

$adminUser = $obj->get('\Magento\User\Model\UserFactory')->create()->loadByUsername($userInfo['username']);
if($adminUser->getId()) {
	echo 'admin user already exist';
} else {
		$userModel = $obj->get('\Magento\User\Model\UserFactory')->create();

		echo 'admin user created successfully';
	} catch (\Exception $ex) {
		echo $ex->getMessage();

Read Also: External File/Script In Magento 2.

Hope this helps.

Leave a Reply

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