When we work in magento with out of box customization then we might need to create/update admin user information programmatically in magento2.

In this blog, We will see how we can create and update admin user information programmatically.

Admin User Create/Update

Here is code for create/update admin user using data patch. We can use similar code in Model or Helper classes.

PHP
<?php

declare(strict_types=1);

namespace MageDad\Module\Setup\Patch\Data;

use Magento\Framework\Setup\Patch\DataPatchInterface;
use Magento\User\Model\UserFactory;

class CreateUserUpdate implements DataPatchInterface
{
    public function __construct(
        private UserFactory $userFactory,
    ) {
    }

    /**
     * {@inheritdoc}
     */
    public function apply()
    {
        $adminInfo = [
            'username'  => 'johndoe',
            'firstname' => 'John',
            'lastname'    => 'Doe',
            'email'     => 'johndoe@johndoe.com',
            'password'  =>'johndoe@123',
            'interface_locale' => 'en_US',
            'is_active' => 1
        ];

        $userModel = $this->userFactory->create();
        $userModel->setData($adminInfo);
        $userModel->setRoleId(1);
        $userModel->save();
        
        # Admin user update code
        $userModel = $this->userFactory->create()->loadByUsername('johndoe');
        # $userModel = $this->userFactory->create()->load($userId);
        $userModel->setFirstname("Johnny");
        $userModel->setLastname("Dost");
        $userModel->save();
    }

    /**
     * {@inheritdoc}
     */
    public static function getDependencies()
    {
        return [];
    }

    /**
     * {@inheritdoc}
     */
    public function getAliases()
    {
        return [];
    }
}

Our aims to write quality blog with tested code so we add this code to GitHub
You can see this GitHub commit of create/update admin user.

I hope this blog is useful to create/update admin user in magento2. In case, I missed anything or need to add some more information, Don’t heisted to leave a comment in this blog, I’ll get back with some positive approach.

Keep loving ❤️ Keep inspiring 🤩 Keep liking 👍 No sharing 😂

Write A Comment