How to set default shipping address of the customer Magento 2?

Set Default shipping address id of the customer in Magento 2 using Address Repository Interface.

You required Customer Id to set shipping address and address id you want to assign it.

First, load the existing address by the getById method of the address repository interface with the set customer.

namespace Jesadiya\SetShippingAddress\Model;

use Psr\Log\LoggerInterface;
use Magento\Customer\Api\AddressRepositoryInterface;
use Magento\Customer\Api\CustomerRepositoryInterface;

class DefaultShipping
     * @var CustomerRepositoryInterface
    private $customerRepository;

     * @var AddressRepositoryInterface
    private $addressRepository;

     * @var LoggerInterface
    private $logger;

    public function __construct(
        CustomerRepositoryInterface $customerRepository,
        AddressRepositoryInterface $addressRepository,
        LoggerInterface $logger
    ) {
        $this->customerRepository = $customerRepository;
        $this->addressRepository = $addressRepository;
        $this->logger = $logger;

     * assign default shipping address
     * @param int $customerId
     * @param int $addressId
     * @return void
    public function setShippingAddress(int $customerId, int $addressId)
        try {
            $address = $this->addressRepository->getById($addressId)->setCustomerId($customerId);

        } catch (\Exception $exception) {

$address->setIsDefaultShipping(true) set the current address id to default address for the given customer.

Call method by required parameter,

$customerId = 10;
$addressId = 5;
$result = $this->setShippingAddress($customerId, $addressId);

When you successfully run the method, you can see the updated address details from the My Account section of the frontend.

  • Database Section:
    customer_entity table stores the address id in the default_shipping column from the database.