How to Create Customers Programmatically in Magento 2
In Magento 2, a new customer account is created via sign up. Also, customer registration is possible via admin panel. But, as a store owner, what if you want to add a huge number of new customers manually? The task becomes tedious as you have to create the customer accounts having different addresses and need to assign them in different groups. It is not feasible to manually create each customer in such case. The smarter way is to get customer data from attribute value in Magento 2 and create customers programmatically in Magento 2.
The method discussed here allows to programmatically create customers and assign to a customer group. Save time and get your task done quickly!
Method to create customers programmatically in Magento 2:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 |
<?php use Magento\Framework\App\Bootstrap; require 'app/bootstrap.php'; $bootstrap = Bootstrap::create(BP, $_SERVER); $objectManager = $bootstrap->getObjectManager(); $state = $objectManager->get('\Magento\Framework\App\State'); $state->setAreaCode('frontend'); $storeManager = $objectManager->get('\Magento\Store\Model\StoreManagerInterface'); $storeId = $storeManager->getStore()->getId(); $websiteId = $storeManager->getStore($storeId)->getWebsiteId(); try { $customer = $objectManager->get('\Magento\Customer\Api\Data\CustomerInterfaceFactory')->create(); $customer->setWebsiteId($websiteId); $customer->setEmail($email); $customer->setFirstname("test first"); $customer->setLastname("test last"); $hashedPassword = $objectManager->get('\Magento\Framework\Encryption\EncryptorInterface')->getHash('MyNewPass', true); $objectManager->get('\Magento\Customer\Api\CustomerRepositoryInterface')->save($customer, $hashedPassword); $customer = $objectManager->get('\Magento\Customer\Model\CustomerFactory')->create(); $customer->setWebsiteId($websiteId)->loadByEmail($email); } catch (Exception $e) { echo $e->getMessage(); } |
You may also love to rea: Create customer using rest API in Magento 2
I’d be happy to assist you in the implementation of the code if you are stuck in the process. Please mention your doubts in the comments section below.
Flash 5 stars if the post is helpful!
Thank you 🙂
Sanjay Jethva
Sanjay is the co-founder and CTO of Meetanshi with hands-on expertise with Magento since 2011. He specializes in complex development, integrations, extensions, and customizations. Sanjay is one the top 50 contributor to the Magento community and is recognized by Adobe.
His passion for Magento 2 and Shopify solutions has made him a trusted source for businesses seeking to optimize their online stores. He loves sharing technical solutions related to Magento 2 & Shopify.
18 Comments
Do you know of a similar process for Magento 1.9? I have a backup of customer data that is in CSV format currently.
Hello red_wallaby,
The above solution will be helpful for you in Magento 2.x only.
Thank You
How can we create new customers from existing data in table, I want to create a customer from the data which I inserted while making CRUD.
Hello Pyaray,
One can use custom code after getting the table data.
You just need to pass the proper value in the particular variable.
Thank You
How can I save a custom field by using this code? I tried $customer->setData(‘custom_field’, $customfield) but it doesn’t work
Hello Friska,
There are two ways you can solve your issue.
1. After line number 29, use the above code and save a customer.
2. Try the below code after customer load by email
$customerRepository = $objectManager->get('\Magento\Customer\Api\CustomerRepositoryInterface');
$customer->setCustomAttribute('customAttribute', 'value');
$customerRepository->save($customer);
Thank you.
This works great in my custom form controller, thank you!
Glad it helped!
Thanks for the appreciation.
I have used this code, but its not working..??Customer is not saving
Hey Gayathri,
I’ve used the above code repeatedly and works fine each time.
The issue might be something else.
Thank you.
where should is add this code?
Hello,
Add this code to the Magento root directory.
Thanks.
I am using the ‘save()’ result in $result and then fetching user id by ‘$result->getId()’. That works ok. One more thing. Let say there comes an error, let say “main.ERROR: A customer with the same email address already exists in an associated website. [] []”, this entry goes into system.log.
Though I am unable to check this error in the $result. Neither it falls into catch block. May you help
Please use the below code to check if the email address already exists:
$customerFactory = $objectManager->get('\Magento\Customer\Model\CustomerFactory')->create();
if ($customerFactory->loadByEmail($email)->getId()) {
$errMesg = 'There is already an account with this email address ' . $email;
}
So does the ‘create()’ method will only create the customer or ‘loadByEmail($email)’ is also necessary? What is the purpose of loadByEmail here? Does ‘setWebsiteId($websiteId)’ is necessary if we are running this code from admin end.
‘create()’ is used for creating Objects and not for customers.
‘loadByEmail($email)’ is not necessary but you can use it if you want to get the customer information using email id.
‘setWebsiteId($websiteId)’ is necessary because you won’t be able to select the website if it’s a Multi-website store.
How can i add event after this … i want to add customer save after event after
After Customer is created, you can call the event “customer_register_success” by creating an object for Event Manager.