Today we are going to focus on extracting customer information based on order id or order entity in Magento 2. We are going to keep this article short and crispy for our Magento 2 developers so let’s crack on with the coding part ????

How to get customer custom attribute using order id in Magento 2?

<?php
use MagentoCustomerApiCustomerRepositoryInterface; class Order
{ /** * @var MagentoCustomerApiCustomerRepositoryInterface */ private $_customerRepository; /** * @param MagentoCustomerApiCustomerRepositoryInterface $customerRepository */ public function __construct( MagentoCustomerApiCustomerRepositoryInterface $customerRepository ) { $this->_customerRepository = $customerRepository; } /** * @param MagentoSalesApiDataOrderInterface $order */ public function getCustomerCustomAttributeValue($order){ $customer = $this->_customerRepository->getById($order->getCustomerId()); if ($customAttribute = $customer->getCustomAttribute('custom_attribute_code')){ $packagingNotes = $customAttribute->getValue(); } }
}

As you can see we are utilising customer repository as we have recommended several times in our previous articles wherever possible try to use repository over factory classes. One of the best practices our developers follow and we promote other developers out there to do the same when you have an option to do so.

The above example is showing how to pull custom attribute from customer’s table but in the similar way you can pull system attribute information as well.

That’s it, Hope this article helped you in some way. Please leave us your comment and let us know what do you think? Thanks.

Similar Posts