Magento 2 – How to Get Customer Address by Address ID

addressmagento2PHPshippingshipping-address

Can i get customer address like picture below with address id? If i can, how should i do it?

customer shipping address

Best Answer

You can get the formatted address using address id with below code:

public function __construct(
    \Magento\Customer\Api\AddressRepositoryInterface $addressRepository,
    \Magento\Customer\Model\Address\Config $addressConfig,
    \Magento\Customer\Model\Address\Mapper $addressMapper,
) {
    $this->addressRepository = $addressRepository;
    $this->_addressConfig = $addressConfig;
    $this->addressMapper = $addressMapper;
}

public function getFormattedAddress($addressId)
{
    try {
        $addressObject = $this->addressRepository->getById($addressId);
        /** @var \Magento\Customer\Block\Address\Renderer\RendererInterface $renderer */
        $renderer = $this->_addressConfig->getFormatByCode('html')->getRenderer();
        return $renderer->renderArray($this->addressMapper->toFlatArray($addressObject));
    } catch (\Magento\Framework\Exception\NoSuchEntityException $e) {
        return null;
    }
}