How to Update a Customer Programmatically in Magento 2

In the previous code snippet, we have seen how to create a customer programmatically in Magento 2. But sometimes you simply need to update some information of a customer like date of birth or gender. In that case, you have to update a customer programmatically in Magento 2.

To update a customer programmatically you have to first load the existing customer by customer id or email. Once you load the existing customer, then you can simply set the new information in the object and save the customer data.

Update a Customer Programmatically in Magento 2

Create a Customer.php model file under your custom module, and add below code.

<?php
namespace Codextblog\Customer\Model;

use Magento\Customer\Api\AccountManagementInterface;
use Magento\Customer\Model\AddressFactory;
use Magento\Customer\Model\CustomerFactory;
use Magento\Customer\Model\ResourceModel\Address;
use Magento\Framework\Exception\AlreadyExistsException;
use Magento\Framework\Exception\LocalizedException;
use Magento\Framework\Exception\NoSuchEntityException;
use Magento\Framework\Stdlib\DateTime\TimezoneInterface;
use Magento\Store\Model\StoreManagerInterface;

class Customer
{
    /**
     * @var AccountManagementInterface
     */
    protected $accountManagement;
    /**
     * @var StoreManagerInterface
     */
    protected $storeManager;
    /**
     * @var CustomerFactory
     */
    protected $customerFactory;
    /**
     * @var \Magento\Customer\Model\ResourceModel\Customer
     */
    protected $customerResource;
    /**
     * @var AddressFactory
     */
    protected $addressFactory;
    /**
     * @var Address
     */
    protected $addressResource;
    /**
     * @var TimezoneInterface
     */
    protected $timezone;

    /**
     * Customer constructor.
     * @param AccountManagementInterface $accountManagement
     * @param StoreManagerInterface $storeManager
     * @param CustomerFactory $customerFactory
     * @param \Magento\Customer\Model\ResourceModel\Customer $customerResource
     * @param AddressFactory $addressFactory
     * @param Address $addressResource
     * @param TimezoneInterface $timezone
     */
    public function __construct(
        AccountManagementInterface $accountManagement,
        StoreManagerInterface $storeManager,
        CustomerFactory $customerFactory,
        \Magento\Customer\Model\ResourceModel\Customer $customerResource,
        AddressFactory $addressFactory,
        Address $addressResource,
        TimezoneInterface $timezone
    ) {
        $this->accountManagement = $accountManagement;
        $this->storeManager = $storeManager;
        $this->customerFactory = $customerFactory;
        $this->customerResource = $customerResource;
        $this->addressFactory = $addressFactory;
        $this->addressResource = $addressResource;
        $this->timezone = $timezone;
    }

    /**
     * @param array $post
     * @param bool $update
     * @return \Magento\Customer\Model\Customer
     * @throws AlreadyExistsException
     * @throws NoSuchEntityException
     * @throws LocalizedException
     */
    public function updateCustomer(array $post, $update = true)
    {
        $store = $this->storeManager->getStore();
        $websiteId = $this->storeManager->getStore()->getWebsiteId();
        $customer = $this->customerFactory->create();

        //load existing customer to update its attribute
        if ($update) {
            $customer->setWebsiteId($websiteId)->loadByEmail($post['email']);
        }
        $customer->setWebsiteId($websiteId)
            ->setStore($store)
            ->setFirstname($post['firstname'])
            ->setLastname($post['lastname'])
            ->setEmail($post['email'])
            ->setForceConfirmed(true);

        $dob = $post['dob'];
        if (!empty($dob)) {
            $dob = $this->timezone->date($dob)->format('Y-m-d');
            $customer->setDob($dob);
        }

        try {
            //update customer
            $this->customerResource->save($customer);
            return $customer;
        } catch (AlreadyExistsException $e) {
            throw new AlreadyExistsException(__($e->getMessage()), $e);
        } catch (\Exception $e) {
            throw new \RuntimeException(__($e->getMessage()));
        }
    }
}

Here inside the updateCustomer function, first we are loading existing customer using email. After loading we are setting its attributes and saving the data.

By following this code, you can easily update the customer data and its attributes programmatically.

Want to ask a question or leave a comment?

Leave a Comment

(0 Comments)

All the comments are goes into moderation before approval. Irrelevant comment with links directly goes to spam. Your email address will not be published.

Was this post helpful? Please support Us!

Follow us on twitter or Like us on facebook.

 


To Avoid Spam Downloads, We Want Your Email

We will send you download link right
away. Please submit form below.
SEND ME DOWNLOAD LINK
Close

Increase Your
Magento 2
Knowledge

Get Weekly Tutorial
to your Inbox
Subscribe Me
close-link
Subscribe Here