How to Create Customer Programmatically in Magento 2

How to Create Customer Programmatically in Magento 2?

Sometimes when you have an offline customer who does not have knowledge of the online structure. In this situation, you might require to create a customer programmatically in Magento 2.

Steps to Create Customer Programmatically in Magento 2

All you need to do is pass the required parameter to the customer array as mentioned below, create a PHP block or helper file and call createCustomer() function:

<?php
$customerInfo =[
 'customer' =>[
 'firstname' => 'MageDelight',
 'email' => '[email protected]', //customer email id
 'lastname' => 'solutions',
 'password' => 'admin123',
 'prefix' => 'The',
 'suffix' => ''
 ]
];
$block->createCustomer($customerInfo);
?>

In Block file, Pass customer required data from above $customerInfo array,

<?php
namespace MD\CreateCustomer\Block;
class Customer extends \Magento\Framework\View\Element\Template
{
 public function __construct(
 \Magento\Framework\View\Element\Template\Context $context,
 \Magento\Store\Model\StoreManagerInterface $storeManager,
 \Magento\Customer\Model\CustomerFactory $customerFactory,
 array $data = []
 ) {
 $this->storeManager = $storeManager;
 $this->customerFactory = $customerFactory;
 parent::__construct($context, $data);
 }
/** Create customer
 * Pass customer data as array
 */
 public function createCustomer($data) {
$store = $this->storeManager->getStore();
 $storeId = $store->getStoreId();
 $websiteId = $this->storeManager->getStore()->getWebsiteId();
 $customer = $this->customerFactory->create();
 $customer->setWebsiteId($websiteId);
 $customer->loadByEmail($data['customer']['email']);// load customer by email address
 if(!$customer->getId()){
 //For guest customer create new cusotmer
 $customer->setWebsiteId($websiteId)
 ->setStore($store)
 ->setFirstname($data['customer']['firstname'])
 ->setLastname($data['customer']['lastname'])
 ->setPrefix($data['customer']['prefix'])
 ->setEmail($data['customer']['email'])
 ->setPassword($data['customer']['password']);
 $customer->save();
 }
 }
}

Now Run Command:

php bin/magento indexer:reindex
php bin/magento cache:flush

Now check if you did it right with the following steps

Go to Admin panel

Login your admin panel with username and password

Click on Customers Tab -> All Customer

There, you have it!

We have covered everything related to creating customer programmatically in Magento 2. Let us know in the comments if we have missed out anything. Feel free to reach us out!

Magento Support Services

Tags