How do we change a customer's email programatically in Magento 2?
1 Answer
Use \Magento\Customer\Api\CustomerRepositoryInterface
to change customer information.
protected $_customerRepositoryInterface;
public function __construct (
...
\Magento\Customer\Api\CustomerRepositoryInterface $customerRepositoryInterface
...
) {
...
$this->_customerRepositoryInterface = $customerRepositoryInterface;
...
}
public function changeCustomerInfo()
{
$customerId = '1'; // customer ID
$customer = $this->_customerRepositoryInterface->getById($customerId);
$customer->setEmail("[email protected]"); //set customer email
$customer->setFirstname("First Name"); //set customer First Name
$customer->setLastname("Last name"); // set customer Last Name
$this->_customerRepositoryInterface->save($customer);
}