Magento, Magento 2

Magento 2 : Get Default Billing and Shipping Address by Customer ID

How to Get Default Billing and Shipping Address by Customer ID in Magento 2

In this tutorial, Today I will explain to how to get default billing and shipping address by customer id in Magento 2. Magento 2 provides functionality that user can add multiple address in customer data. But, when you want to get default billing and shipping address of the customer then how to get that address? Let’s follow the steps to get that address.

You may also like this :

1) First of all, Let’s assume that you have created simple module. Now, I added code in block class. Just copy from below and paste it :

<?php

namespace RH\CustomerModule\Block;

class AddressBook extends \Magento\Framework\View\Element\Template
{
    /**
     * @var Magento\Customer\Api\AccountManagementInterface
     */
    protected $accountManagement;

    /**
     * @param  \Magento\Framework\View\Element\Template\Context $context
     * @param  \Magento\Customer\Api\AccountManagementInterface $accountManagement
     * @param  array                                            $data
     */
    public function __construct(
        \Magento\Framework\View\Element\Template\Context $context,
        \Magento\Customer\Api\AccountManagementInterface $accountManagement,
        array $data = []
    ) {
        $this->accountManagement = $accountManagement;
        parent::__construct($context, $data);
    }

    public function getDefaultShippingAddress($customerId)
    {
        try {
            $address = $this->accountManagement->getDefaultShippingAddress($customerId);
        } catch (NoSuchEntityException $e) {
            return __('You have not added default shipping address. Please add default shipping address.');
        }
        return $address;
    }

    public function getDefaultBillingAddress($customerId)
    {
        try {
            $address = $this->accountManagement->getDefaultBillingAddress($customerId);
        } catch (NoSuchEntityException $e) {
            return __('You have not added default billing address. Please add default billing address.');
        }
        return $address;
    }
}

You can see on above code that there are getDefaultShippingAddress() and getDefaultShippingAddress() function available. You can call in anywhere and pass customer ID in that function. After that, you will get default billing and shipping address of customer.

2) Now, just removed generated folder and cache clean.

That’s it !!!

I hope this blog is easy to understand about how to get default billing and shipping address by customer id in Magento 2. In case, I missed anything or need to add some information, always feel free to leave a comment in this blog, I’ll get back with proper solution.

Stay Safe and Stay Connected !!

Tagged ,