Programmatically update customer data in Magento 2

Sometimes we may require to update customer information programmatically in Magento 2. It’s very simple. In this blog, I am going to explain how to update customer information in Magento 2 programmatically.

In the below example, I will be using both Dependency Injection (DI) and Object Manager to update the customer information in Magento 2. But Magento recommends using the dependency injection instead of the object manager.

Using Dependency Injection (DI)

Here is the example code to update customer data in Magento 2 using dependency injection.

In this, we might need to inject the object of \Magento\Customer\Api\CustomerRepositoryInterface class in the constructor of our module’s class.

protected $customerRepository;

public function __construct(
    ------------------
    \Magento\Customer\Api\CustomerRepositoryInterface $customerRepository,
    -----------------
) {
    ------------
    $this->customerRepository = $customerRepository;
    -----------
}

public function execute()
{
    $websiteId = 2;
    // load customer info by email
    $customer = $this->customerRepository->get('roni_cost@example.com', $websiteId);

    // load customer info by id    
    $customer = $this->customerRepository->getById(12);

    // Update customer info
    $customer->setFirstname('Roni');
    $customer->setLastname('Cost');
    $customer->setEmail('roni_cost@test.com');

    $customer->setCustomAttribute('abc', 'attribute value');

    $this->customerRepository->save($customer);
}

Using Object Manager

Here is the example code to update customer data in Magento 2 using object manager.

$storeManager = $objectManager->get('\Magento\Store\Model\StoreManagerInterface');
$websiteId = $storeManager->getStore()->getWebsiteId();

$objectManager = \Magento\Framework\App\ObjectManager::getInstance();
$customerRepository = $objectManager->create('Magento\Customer\Api\CustomerRepositoryInterface');

// load customer info by email
$customer = $customerRepository->get('roni_cost@example.com', $websiteId);

// load customer info by id    
$customer = $customerRepository->getById(12);

// Update customer Info
$customer->setFirstname('Roni');
$customer->setLastname('Cost');
$customer->setEmail('roni_cost@test.com');

$customer->setCustomAttribute('abc', 'attribute value');

$customerRepository->save($customer);

Hope this helps.

One Comment on “Programmatically update customer data in Magento 2”

Leave a Reply

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