Magento 2 – customer get default billing and shipping address
In this tutorial I show you how to get default billing and shipping address by customer. That is need if you want to create or update customers programmatically. A customer can have many different addresses in Magento 2 address book, but only one can set as default billing and one to default shipping. If you don’t know how to get customer, please read my get customer by collection post first.
Magento 2 – customer get default billing and shipping address
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 | class SetCustomer { protected $_customerFactory; protected $_addressFactory; public function __construct(\Magento\Customer\Model\CustomerFactory $customerFactory, \Magento\Customer\Model\AddressFactory $addressFactory ) { $this->_customerFactory = $customerFactory; $this->_addressFactory = $addressFactory; } //get customer model before you can get its address data $customer = $customerFactory->create()->load(1); //insert customer id //billing $billingAddressId = $customer->getDefaultBilling(); $billingAddress = $this->_addressFactory->create()->load($billingAddressId); //now you can update your address here and don't forget to save $billingAddress->save(); //shipping $shippingAddressId = $customer->getDefaultShipping(); $shippingAddress = $this->_addressFactory->create()->load($shippingAddressId); //now you can update your address here and don't forget to save $shippingAddress->save(); |
As you can see, it is quite easy to get or set billing or shipping address by customer object. In this sample code we need to inject customer factory to get a customer object and address factory get an address by its id. You can easily get default billing or shipping address id from a customer by calling its getDefaultBilling() or getDefaultShipping() functions. You can change or only get address data and if needed save it back to database.
Create new address
If you want to create a new address for a customer and set it as default shipping or billing address, you only need to create a new address object from factory:
1 | $address = $this->_addressFactory->create(); |
An set its data. Depending on its type you need to set it as default shipping or default billing. You can also set both, so that a customer has only one address:
1 2 3 4 | if($type == "shipping") $address->setIsDefaultShipping('1'); if($type == "billing") $address->setIsDefaultBilling('1'); |
Conclusion
In this small post I showed you how to set or get default billing and shipping address from a customer by code. If you are working on an import, you may need this code. You can manipulate customer address data easily. Injected factories are an easy way to use Magento 2 models and this method is much better than getting it from object manager.