magento2: $order->getCustomer() returns NULL for registered customer
Preconditions (*)
- Magento 2.3.2 & 2.4-develop, community edition
Steps to reproduce (*)
- Create customer account and make an order
- Create a module with an observer to
sales_order_save_after
event
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:Event/etc/events.xsd">
<event name="sales_order_save_after">
<observer name="my-observer" instance="Something\Darkside\Observer\OrderSaveAfter" />
</event>
</config>
- Try to access Customer object from order object
public function execute(Observer $observer): void
{
/** @var Order $order */
$order = $observer->getEvent()->getOrder();
$customer = $order->getCustomer();
....
Expected result (*)
- Method
getCustomer
should return customer object, as defined in phpdoc block OR phpdoc block should be changed to highlight thatNULL
could be returned
Actual result (*)
- Method
getCustomer
always returnsNULL
, but it’s not highlighted in phpdoc block that it could return null
Additional info
Method getCustomer
will return customer only in case if someone added it to Order object, in other cases it doesn’t exists. In case if you need to get customer from the Order object you need to do following get customer ID from the order object
$customerId = $order->getCustomerId();
// $customerId could be NULL in case if order was placed as guest
$customer = $customerId ? $this->customerRepository->getById($customerId) : null;
Where $this->customerRepository
is instance of \Magento\Customer\Api\CustomerRepositoryInterface
that retrieved via constructor
About this issue
- Original URL
- State: closed
- Created 5 years ago
- Comments: 25 (12 by maintainers)
@ihor-sviziev thanks for contributing! I have updated the description.
@engcom-Hotel i think we expected result should be changed, that magic method should highlight that it could return null. This is not direct responsibility of order object to retrieve customer. In client code customer could be retrieved by customerId. Btw both methods getCustomer and getCustomerId might return null in case when order were placed as guest, and that would be absolutely valid behavior