Skip to content

$order->getCustomer() returns NULL for registered customer #25268

Closed
@jakwinkler

Description

@jakwinkler

Preconditions (*)

  1. Magento 2.3.2 & 2.4-develop, community edition

Steps to reproduce (*)

  1. Create customer account and make an order
  2. 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>
  1. 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 (*)

  1. Method getCustomer should return customer object, as defined in phpdoc block OR phpdoc block should be changed to highlight that NULL could be returned

Actual result (*)

  1. Method getCustomer always returns NULL, 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

Metadata

Metadata

Assignees

Labels

Area: FrontendComponent: CustomerComponent: SalesFixed in 2.4.xThe issue has been fixed in 2.4-develop branchIssue: Clear DescriptionGate 2 Passed. Manual verification of the issue description passedIssue: ConfirmedGate 3 Passed. Manual verification of the issue completed. Issue is confirmedIssue: Format is validGate 1 Passed. Automatic verification of issue format passedIssue: Ready for WorkGate 4. Acknowledged. Issue is added to backlog and ready for developmentPartner: i95DevReproduced on 2.4.xThe issue has been reproduced on latest 2.4-develop branchpartners-contributionPull Request is created by Magento Partner

Type

No type

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions