Delete Customer address by address id in Magento 2 to delete extra customer addresses for the customer account.
Like, A customer has multiple redundant addresses and wants to delete the customer address, You can delete the address by id programmatically.
Code snippet to delete customer address,
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 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 | <?php namespace Jesadiya\DeleteAddress\Model; use Exception; use Psr\Log\LoggerInterface; use Magento\Framework\Exception\LocalizedException; use Magento\Customer\Api\AddressRepositoryInterface; class DeleteAddressById { /** * @var AddressRepositoryInterface */ protected $addressRepositoryInterface; /** * @var LoggerInterface */ private $logger; public function __construct( LoggerInterface $logger, AddressRepositoryInterface $addressRepositoryInterface ) { $this->logger = $logger; $this->addressRepositoryInterface = $addressRepositoryInterface; } /** * Delete customer address. * * @param int $addressId * @return bool * @throws LocalizedException */ public function deleteCustomerAddress($addressId) { $addressRepository = null; try { $addressRepository = $this->addressRepositoryInterface->deleteById($addressId); } catch (Exception $exception) { $this->logger->error($exception->getMessage()); } return $addressRepository; } } |
Pass Customer address id as a parameter to delete specific customer address from the system,
1 2 | $addressId = (int)1; $customerAddress = $this->deleteCustomerAddress($addressId); |
Output:
Boolean value
If Address deletes successfully return true otherwise false.