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,
<?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,
$addressId = (int)1; $customerAddress = $this->deleteCustomerAddress($addressId);
Output:
Boolean value
If Address deletes successfully return true otherwise false.