Site icon MageComp Blog

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

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

Hello Magento Friends,

Today, I have come up with a solution to get default billing and shipping addresses by customer ID in Magento 2.

Magento 2 allows customers to have multiple billing and shipping addresses associated with their account. Each of these addresses can be used during the checkout process, providing flexibility for customers with different shipping or billing requirements. 

Learn – How to Configure Multiple Shipping Addresses in Magento 2.

Customers can also have default billing and shipping addresses set in their customer accounts. Customers can have only one default billing and one default shipping address at a time. These addresses are convenient for returning customers as they can quickly select them during the checkout process, but customers can always choose to enter a new address if needed.

Let’s find out How to Get Default Billing and Shipping Address by Customer ID in Magento 2.

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

Step 1: Create a block file at the given path below.

{{magento_root}}\app\code\Vendor\Extension\Block\AddressBook.php

Now add the code as follows.

<?php

namespace Vendor\Extension\Block;

class AddressBook extends \Magento\Framework\View\Element\Template
{
    protected $accountManagement;

    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.');
        }
        return $address;
    }

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

Conclusion:

This way, you can get the default billing and shipping address by customer ID in Magento 2. If you have any doubts about the above method or if you face any errors, connect with me through the comment section. Share the tutorial with your friends and stay in touch with us so that you do not miss out on any important Magento solution from us.

Happy Coding!

Exit mobile version