How To

How to assign guest customers orders into registered account in Magento 2

In this article, I will help you to learn How to assign guest customer’s orders into a registered account in Magento 2. Also don’t forget to check our previously published How to Add Discount Component to Checkout Order Summary in Magento 2

Basically when any customer places an order from your store being a guest customer and later on that customer registers themself in your store then the orders they place being the guest customers don’t reflect on their account. Therefore to add these orders to the registered account you will require to add the below-given codes into the custom extension.

Steps to assign guest customers orders into registered account in Magento 2:

Step 1: Create Events.xml in the following path

app\code\Vendor\Extension\etc\events.xml

<?xml version="1.0"?>

<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:Event/etc/events.xsd">

    <event name="customer_save_after_data_object">

        <observer name="customer_save" instance="Vendor\Extension\Observer\Customersave" />

    </event>

</config>

Step 2: Now add Customersave.php in the following path

app\code\Vendor\Extension\Observer\Customersave.php

<?php

namespace Vendor\Extension\Observer;

use Magento\Framework\Event\ObserverInterface;

class Customersave implements ObserverInterface

{

    protected $collectionFactory;

    protected $logger;

    public function __construct(

        \Magento\Sales\Model\ResourceModel\Order\CollectionFactory $collectionFactory,

        \Psr\Log\LoggerInterface $logger

    )

    {

        $this->collectionFactory = $collectionFactory;

        $this->logger = $logger;

    }

    public function execute(\Magento\Framework\Event\Observer $observer)

    {

        try {

            $savedCustomer = $observer->getData('customer_data_object');                  

            $collection = $this->collectionFactory->create()

                ->addAttributeToSelect('entity_id')

                ->addAttributeToSelect('customer_email')

                ->addFieldToFilter('customer_email',

                    ['eq' => $savedCustomer->getEmail()]

                )->addFieldToFilter('customer_is_guest',

                    ['eq' => 1]

                );

            if ($collection->count()) {

                foreach ($collection as $order){

                     $order->setCustomerId($savedCustomer->getId());

                     $order->setCustomerGroupId($savedCustomer->getGroupId());

                     $order->setCustomerIsGuest(1);

                     $order->save();

                }

            }

            return $this;

        } catch (\Exception $e) {

            $this->logger->critical($e->getMessage());

        }

    }

}

Note: The above codes may take the load when the customer registers all the registered customer’s order details loads to set the customer id to each order.

Therefore, we will use the below method to reduce the load. Here we have used raw query so in a single query we will set it to multiple orders.

<?php

namespace Vendor\Extension\Observer;

use Magento\Framework\Event\ObserverInterface;

class Customersave implements ObserverInterface

{

    protected $collectionFactory;

    protected $resourceConnection;

    protected $logger;

    public function __construct(

        \Magento\Sales\Model\ResourceModel\Order\CollectionFactory $collectionFactory,

        \Magento\Framework\App\ResourceConnection $resourceConnection,

        \Psr\Log\LoggerInterface $logger

    )

    {

        $this->collectionFactory = $collectionFactory;

        $this->resourceConnection = $resourceConnection;

        $this->logger = $logger;

    }

    public function execute(\Magento\Framework\Event\Observer $observer)

    {

        try {

            $savedCustomer = $observer->getData('customer_data_object');

            $collection = $this->collectionFactory->create()

                ->addAttributeToSelect('entity_id')

                ->addAttributeToSelect('customer_email')

                ->addFieldToFilter('customer_email',

                    ['eq' => $savedCustomer->getEmail()]

                )->addFieldToFilter('customer_is_guest',

                    ['eq' => 1]

                );

            if ($collection->count()) {

                $gustOrderId = "";

                foreach ($collection as $item) {

                    $gustOrderId .= $item->getId() . ",";

                }

                $gustOrderId = rtrim($gustOrderId, ',');

                $tableName = $this->getTableName('sales_order');

                $sql = "UPDATE $tableName SET `customer_id` = " . $savedCustomer->getId() . ",customer_is_guest = 0,customer_group_id =" . $savedCustomer->getGroupId() . " WHERE $tableName.`entity_id` IN (" . $gustOrderId . ")";

                $this->resourceConnection->getConnection()->query($sql);

                $tableName = $this->getTableName('sales_order_grid');

                $sql = "UPDATE $tableName SET `customer_id` = " . $savedCustomer->getId() . ",customer_group=" . $savedCustomer->getGroupId() . " WHERE $tableName.`entity_id` IN (" . $gustOrderId . ")";

                $this->resourceConnection->getConnection()->query($sql);

            }

            return $this;

        } catch (\Exception $e) {

            $this->logger->critical($e->getMessage());

        }

    }

    public function getTablename($tableName)

    {

        $connection = $this->resourceConnection->getConnection();

        $tableName = $connection->getTableName($tableName);

        return $tableName;

    }

}

That’s It.

Wrap Up:

Expectantly, all are able to implement the above illustration without any difficulties. To automate this functionality without following the complicated codes integrate the Magento 2 Assign Order to Customer extension.

In case of any errors you come through in between the implementation then let me know in the comment section below I will solve them out there. 

Share the illustration with your Magento Developer Friends.

Happy Reading.

Click to rate this post!
[Total: 4 Average: 5]
Dhiren Vasoya

Dhiren Vasoya is a Director and Co-founder at MageComp, Passionate ?️ Certified Magento Developer?‍?. He has more than 9 years of experience in Magento Development and completed 850+ projects to solve the most important E-commerce challenges. He is fond❤️ of coding and if he is not busy developing then you can find him at the cricket ground, hitting boundaries.?

Recent Posts

Generating Thumbnails with Spatie Media Library in Laravel 11: A Step-by-Step Guide

Generating image thumbnails is a common requirement in web applications, especially when handling media-heavy content.…

19 hours ago

Enhancing Web Application Security with Laravel’s Built-In Features

In today’s digital landscape, web application security is paramount. As a powerful PHP framework, Laravel…

2 days ago

Magento 2 Extensions Digest October 2024 (New Release & Updates)

October was an exciting month for MageComp! From significant updates across our Magento 2 extension…

2 days ago

Improving Error Handling and Transition Management in Remix with useRouteError and useViewTransitionState

In modern web development, seamless navigation and state management are crucial for delivering a smooth…

1 week ago

Magento Open Source 2.4.8-Beta Release Notes

Magento Open Source 2.4.8 beta version released on October  8, 2024. The latest release of…

2 weeks ago

How to Create Catalog Price Rule in Magento 2 Programmatically?

Hello Magento Friends, Creating catalog price rules programmatically in Magento 2 can be a valuable…

2 weeks ago