1

I want to know how to get the default billing and shipping address of a customer as an array.

For example, the code below:

$customer = $this->customerFactory->create()->load($customer_id);
$var_dump($customer-getData());

returns an array containing the customer information:

array(28) {
["entity_id"]=>
string(1) "1"
["website_id"]=>
string(1) "1"
["email"]=>
string(21) "[email protected]"
["group_id"]=>
string(1) "1"
["increment_id"]=>
NULL
["store_id"]=>
string(1) "1"
["created_at"]=>
string(19) "2018-03-24 21:49:15"
["updated_at"]=>
string(19) "2018-03-24 21:49:16"
["is_active"]=>
string(1) "1"
["disable_auto_group_change"]=>
string(1) "0"
["created_in"]=>
string(18) "Default Store View"
["prefix"]=>
NULL
["firstname"]=>
string(8) "Veronica"
["middlename"]=>
NULL
["lastname"]=>
string(8) "Costello"
["suffix"]=>
NULL
["dob"]=>
string(10) "1973-12-15"
["password_hash"]=>
string(99) "717e603af8497aafda595916332ee0c14a4e84ea59c4a6c3b92a010d747d5547:hHG7t2EQBdl6rZihGuCRxYAguCMCZOya:1"
["rp_token"]=>
string(32) "b7fc3de75f6bf6444abf72f2fb9bc157"
["rp_token_created_at"]=>
string(19) "2018-03-24 21:49:16"
["default_billing"]=>
string(1) "1"
["default_shipping"]=>
string(1) "1"
["taxvat"]=>
NULL
["confirmation"]=>
NULL
["gender"]=>
string(1) "2"
["failures_num"]=>
string(1) "0"
["first_failure"]=>
NULL
["lock_expires"]=>
NULL
}

Now, if I want to do the same for address:

$address = $this->addressFactory->create()->load($customer->getDefaultBilling);
$var_dump($address-getData());

This also returns an array, but it's way larger than the customer one to the point that it crashes the browser.

I just need the default billing and shipping address as an array without any other data.

Thank you.

1 Answer 1

2

First initialize CustomerRepository and AddressCollectionFactory in your constructor

\Magento\Customer\Api\CustomerRepositoryInterface

\Magento\Customer\Model\ResourceModel\Address\CollectionFactory

you can get your array like this

$customer_id = 5;

$customer = $this->customerRepository->getById($customer_id);
$billing_address_id = $customer->getDefaultBilling();



$addressCollection = $this->addressCollectionFactory->create()
->addAttributeToFilter("entity_id",$billing_address_id)
    ->getFirstItem();
print_r($addressCollection->getData());

This will print the billing address array

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.