Delete Customer Account Programmatically in Magento 2 CE

customerdeletemagento-2.1

Version: Magento 2.1.0

I run the following codes in my controller and got error:

$customer = $this->customerFactory->create()->load($id);
$customer->delete();

Error:

Exception #0 (Magento\Framework\Exception\LocalizedException): Delete operation is forbidden for current area

My code was stopped by the beforeDelete() method in Magento\Framework\Model\AbstractModel.php. It calls another method called isAllowed(AbstractModel $model)

How do I bypass these methods and delete a customer?

Best Answer

Customer delete operation is valid from admin only. When you perform delete operation, magento check isSecureArea is true/false. So you can assign isSecureArea by following way:

/**
 * @var \Magento\Framework\Registry
 */
protected $registry;

/**
 * @param Context $context
 * @param PageFactory $resultPageFactory
 */
public function __construct(
    \Magento\Framework\Registry $registry
) {
    $this->registry = $registry;
}

Now change your code following way:

$this->registry->register('isSecureArea', true);
$customer = $this->customerFactory->create()->load($id);
$customer->delete();

Clear cache.

Related Topic