Get customers latest order?How to get order from customer Magento 2?Get Customer information from order Magento 2Magento 2 get Order Collection and product skuHow to delete orders in Magento 2.2.1 without any extension?How to get the language code of an order?Magento2: REST API GET all OrdersGet all order details from getItems() / getAllItems() / getAllVisibleItems()Getting order id for guest checkout orderCustomers grid issueHow to get 5 latest order in home page in Magento 2?

German idiomatic equivalents of 能骗就骗 (if you can cheat, then cheat)

Why are symbols not written in words?

How can solar sailed ships be protected from space debris?

Does the Grothendieck group of finitely generated modules form a commutative ring where the multiplication structure is induced from tensor product?

Why are examinees often not allowed to leave during the start and end of an exam?

Why can't i use !(single pattern) in zsh even after i turn on kshglob?

To “Er” Is Human

SQL Server Ignoring Instance name when using port number of different instance

How can I change my buffer system for protein purification?

Odd PCB Layout for Voltage Regulator

Square wave to sawtooth wave using two BJT

Why should I allow multiple IP addresses on a website for a single session?

Is there a connection between representation theory and PDEs?

Are the Gray and Death Slaad's Bite and Claw attacks magical?

Are all notation equal by derivatives?

Which are more efficient in putting out wildfires: planes or helicopters?

How to idiomatically express the idea "if you can cheat without being caught, do it"

Did the Shuttle payload bay have illumination?

How come having a Deathly Hallow is not a big deal?

What was the point of separating stdout and stderr?

Merging two data frames into a new one with unique items marked with 1 or 0

How useful would a hydroelectric power plant be in the post-apocalypse world?

Is this house-rule removing the increased effect of cantrips at higher character levels balanced?

Find the closest three-digit hex colour



Get customers latest order?


How to get order from customer Magento 2?Get Customer information from order Magento 2Magento 2 get Order Collection and product skuHow to delete orders in Magento 2.2.1 without any extension?How to get the language code of an order?Magento2: REST API GET all OrdersGet all order details from getItems() / getAllItems() / getAllVisibleItems()Getting order id for guest checkout orderCustomers grid issueHow to get 5 latest order in home page in Magento 2?













0















How on earth do I programatically retrieve customers latest order?



Tried a few solutions on the web, but they all get all orders from a customer, not all.










share|improve this question


























    0















    How on earth do I programatically retrieve customers latest order?



    Tried a few solutions on the web, but they all get all orders from a customer, not all.










    share|improve this question
























      0












      0








      0








      How on earth do I programatically retrieve customers latest order?



      Tried a few solutions on the web, but they all get all orders from a customer, not all.










      share|improve this question














      How on earth do I programatically retrieve customers latest order?



      Tried a few solutions on the web, but they all get all orders from a customer, not all.







      magento2






      share|improve this question













      share|improve this question











      share|improve this question




      share|improve this question










      asked Sep 26 '18 at 11:41









      BawsiBawsi

      988 bronze badges




      988 bronze badges




















          4 Answers
          4






          active

          oldest

          votes


















          1














          You can try the below code:



          $objectManager = MagentoFrameworkAppObjectManager::getInstance();
          $order = $objectManager->get('MagentoSalesModelOrder')->getCollection()->addFieldToFilter('customer_id',your-customer-id)->setOrder('entity_id','DESC')->getFirstItem();
          echo '<pre>'; print_r($order->getData());


          OR



          $objectManager = MagentoFrameworkAppObjectManager::getInstance();
          $order = $objectManager->get('MagentoSalesModelOrder')->getCollection()->addFieldToFilter('customer_id',your-customer-id)->setOrder('created_at','DESC')->getFirstItem();
          echo '<pre>'; print_r($order->getData());





          share|improve this answer























          • Yep, only thing that worked, was getting the logged in users latest order. Any idea why the default didnt work and returned NULL?

            – Bawsi
            Sep 26 '18 at 12:21


















          0














          I can suggest you an sql query for it which you can execute in your Magento 2 instance:



          SELECT * FROM `sales_order` WHERE customer_id = 'your_customer_id' ORDER BY entity_id DESC LIMIT 1





          share|improve this answer






























            0














            You can get the latest order of below code



            • First Create an order collection.

            • The filter that Collection by Customer ID.

            • Sort that collection by created_at desc. setOrder('created_at', 'desc')

            • make the collection page size 0,1 by below code using setPageSize(1),setCurPage(1)

            `



            <?php

            namespace NameSpace;

            class LastestOrder

            /**
            * @var MagentoSalesModelResourceModelOrderCollectionFactory
            */
            protected $orderCollectionFactory;

            public function __construct(
            MagentoSalesModelResourceModelOrderCollectionFactory $orderCollectionFactory
            )


            $this->orderCollectionFactory = $orderCollectionFactory;

            public function getLastestOrder()

            /**
            * MagentoSalesModelResourceModelOrderCollectionFactory $this->orderCollectionFactor
            */
            $orders = $this->orderCollectionFactory->create();
            //Add all field to Collection
            $orders->addFieldToSelect('*');
            // Collection filter by Customer Id
            $orders->addFieldToSelect('customer_id',$customerId);
            // sort order by create date descending
            $orders->setOrder('created_at','desc');
            // limit collection to 1
            $orders->setPageSize(1)->setCurPage(1);
            if($orders->count() > 0)
            $lastestOrder = $orders->getFirstItem();
            return $lastestOrder;
            else
            // no order found
            $lastestOrder = false;




            `





            share|improve this answer
































              0














              Use this code to get customer's last order and then any order info:



              use MagentoSalesModelOrderRepository;
              use MagentoFrameworkApiFilterBuilder;
              use MagentoFrameworkApiSearchCriteriaBuilder;
              use MagentoFrameworkApiSortOrderBuilder;

              public function __construct(
              OrderRepository $orderRepository,
              SearchCriteriaBuilder $searchCriteriaBuilder,
              FilterBuilder $filterBuilder,
              SortOrderBuilder $sortOrderBuilder
              )
              $this->orderRepository = $orderRepository;
              $this->searchCriteriaBuilder = $searchCriteriaBuilder;
              $this->filterBuilder = $filterBuilder;
              $this->sortOrderBuilder = $sortOrderBuilder;


              /**
              * @param int $customerId
              * @return OrderSearchResultInterface
              */
              public function getCustomerOrders(int $customerId): OrderSearchResultInterface

              $this->searchCriteriaBuilder->addFilter(OrderInterface::CUSTOMER_ID, $customerId);
              $this->searchCriteriaBuilder->addFilter(OrderInterface::STATUS, ['canceled', 'holded'], 'nin');
              $searchCriteria = $this->searchCriteriaBuilder->create();
              $searchCriteria->setSortOrders(
              [
              $this->sortOrderBuilder
              ->setField(OrderInterface::CREATED_AT)
              ->setDirection(SortOrder::SORT_DESC)
              ->create()
              ]
              );
              $searchResults = $this->orderRepository->getList($searchCriteria);

              return $searchResults;


              public function getLastOrder()

              $result = null;
              $searchResults = $this->getCustomerOrders(<customer_id_here>);

              if ($searchResults->getTotalCount() > 0)
              $orders = $searchResults->getList();
              /** @var MagentoSalesModelOrder $lastOrder */
              $lastOrder = reset($orders);
              $result = $lastOrder;

              return $result;






              share|improve this answer























              • Donot past same content to two different questions.it creates an auto-generate duplicate flag. Please change some content to avoid this issue.

                – Amit Bera
                Jun 26 at 3:39













              Your Answer








              StackExchange.ready(function()
              var channelOptions =
              tags: "".split(" "),
              id: "479"
              ;
              initTagRenderer("".split(" "), "".split(" "), channelOptions);

              StackExchange.using("externalEditor", function()
              // Have to fire editor after snippets, if snippets enabled
              if (StackExchange.settings.snippets.snippetsEnabled)
              StackExchange.using("snippets", function()
              createEditor();
              );

              else
              createEditor();

              );

              function createEditor()
              StackExchange.prepareEditor(
              heartbeatType: 'answer',
              autoActivateHeartbeat: false,
              convertImagesToLinks: false,
              noModals: true,
              showLowRepImageUploadWarning: true,
              reputationToPostImages: null,
              bindNavPrevention: true,
              postfix: "",
              imageUploader:
              brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
              contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
              allowUrls: true
              ,
              onDemand: true,
              discardSelector: ".discard-answer"
              ,immediatelyShowMarkdownHelp:true
              );



              );













              draft saved

              draft discarded


















              StackExchange.ready(
              function ()
              StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fmagento.stackexchange.com%2fquestions%2f243900%2fget-customers-latest-order%23new-answer', 'question_page');

              );

              Post as a guest















              Required, but never shown

























              4 Answers
              4






              active

              oldest

              votes








              4 Answers
              4






              active

              oldest

              votes









              active

              oldest

              votes






              active

              oldest

              votes









              1














              You can try the below code:



              $objectManager = MagentoFrameworkAppObjectManager::getInstance();
              $order = $objectManager->get('MagentoSalesModelOrder')->getCollection()->addFieldToFilter('customer_id',your-customer-id)->setOrder('entity_id','DESC')->getFirstItem();
              echo '<pre>'; print_r($order->getData());


              OR



              $objectManager = MagentoFrameworkAppObjectManager::getInstance();
              $order = $objectManager->get('MagentoSalesModelOrder')->getCollection()->addFieldToFilter('customer_id',your-customer-id)->setOrder('created_at','DESC')->getFirstItem();
              echo '<pre>'; print_r($order->getData());





              share|improve this answer























              • Yep, only thing that worked, was getting the logged in users latest order. Any idea why the default didnt work and returned NULL?

                – Bawsi
                Sep 26 '18 at 12:21















              1














              You can try the below code:



              $objectManager = MagentoFrameworkAppObjectManager::getInstance();
              $order = $objectManager->get('MagentoSalesModelOrder')->getCollection()->addFieldToFilter('customer_id',your-customer-id)->setOrder('entity_id','DESC')->getFirstItem();
              echo '<pre>'; print_r($order->getData());


              OR



              $objectManager = MagentoFrameworkAppObjectManager::getInstance();
              $order = $objectManager->get('MagentoSalesModelOrder')->getCollection()->addFieldToFilter('customer_id',your-customer-id)->setOrder('created_at','DESC')->getFirstItem();
              echo '<pre>'; print_r($order->getData());





              share|improve this answer























              • Yep, only thing that worked, was getting the logged in users latest order. Any idea why the default didnt work and returned NULL?

                – Bawsi
                Sep 26 '18 at 12:21













              1












              1








              1







              You can try the below code:



              $objectManager = MagentoFrameworkAppObjectManager::getInstance();
              $order = $objectManager->get('MagentoSalesModelOrder')->getCollection()->addFieldToFilter('customer_id',your-customer-id)->setOrder('entity_id','DESC')->getFirstItem();
              echo '<pre>'; print_r($order->getData());


              OR



              $objectManager = MagentoFrameworkAppObjectManager::getInstance();
              $order = $objectManager->get('MagentoSalesModelOrder')->getCollection()->addFieldToFilter('customer_id',your-customer-id)->setOrder('created_at','DESC')->getFirstItem();
              echo '<pre>'; print_r($order->getData());





              share|improve this answer













              You can try the below code:



              $objectManager = MagentoFrameworkAppObjectManager::getInstance();
              $order = $objectManager->get('MagentoSalesModelOrder')->getCollection()->addFieldToFilter('customer_id',your-customer-id)->setOrder('entity_id','DESC')->getFirstItem();
              echo '<pre>'; print_r($order->getData());


              OR



              $objectManager = MagentoFrameworkAppObjectManager::getInstance();
              $order = $objectManager->get('MagentoSalesModelOrder')->getCollection()->addFieldToFilter('customer_id',your-customer-id)->setOrder('created_at','DESC')->getFirstItem();
              echo '<pre>'; print_r($order->getData());






              share|improve this answer












              share|improve this answer



              share|improve this answer










              answered Sep 26 '18 at 12:10









              Sukumar GoraiSukumar Gorai

              7,6043 gold badges7 silver badges31 bronze badges




              7,6043 gold badges7 silver badges31 bronze badges












              • Yep, only thing that worked, was getting the logged in users latest order. Any idea why the default didnt work and returned NULL?

                – Bawsi
                Sep 26 '18 at 12:21

















              • Yep, only thing that worked, was getting the logged in users latest order. Any idea why the default didnt work and returned NULL?

                – Bawsi
                Sep 26 '18 at 12:21
















              Yep, only thing that worked, was getting the logged in users latest order. Any idea why the default didnt work and returned NULL?

              – Bawsi
              Sep 26 '18 at 12:21





              Yep, only thing that worked, was getting the logged in users latest order. Any idea why the default didnt work and returned NULL?

              – Bawsi
              Sep 26 '18 at 12:21











              0














              I can suggest you an sql query for it which you can execute in your Magento 2 instance:



              SELECT * FROM `sales_order` WHERE customer_id = 'your_customer_id' ORDER BY entity_id DESC LIMIT 1





              share|improve this answer



























                0














                I can suggest you an sql query for it which you can execute in your Magento 2 instance:



                SELECT * FROM `sales_order` WHERE customer_id = 'your_customer_id' ORDER BY entity_id DESC LIMIT 1





                share|improve this answer

























                  0












                  0








                  0







                  I can suggest you an sql query for it which you can execute in your Magento 2 instance:



                  SELECT * FROM `sales_order` WHERE customer_id = 'your_customer_id' ORDER BY entity_id DESC LIMIT 1





                  share|improve this answer













                  I can suggest you an sql query for it which you can execute in your Magento 2 instance:



                  SELECT * FROM `sales_order` WHERE customer_id = 'your_customer_id' ORDER BY entity_id DESC LIMIT 1






                  share|improve this answer












                  share|improve this answer



                  share|improve this answer










                  answered Sep 26 '18 at 11:52









                  Sourabh Kumar SharmaSourabh Kumar Sharma

                  6693 silver badges16 bronze badges




                  6693 silver badges16 bronze badges





















                      0














                      You can get the latest order of below code



                      • First Create an order collection.

                      • The filter that Collection by Customer ID.

                      • Sort that collection by created_at desc. setOrder('created_at', 'desc')

                      • make the collection page size 0,1 by below code using setPageSize(1),setCurPage(1)

                      `



                      <?php

                      namespace NameSpace;

                      class LastestOrder

                      /**
                      * @var MagentoSalesModelResourceModelOrderCollectionFactory
                      */
                      protected $orderCollectionFactory;

                      public function __construct(
                      MagentoSalesModelResourceModelOrderCollectionFactory $orderCollectionFactory
                      )


                      $this->orderCollectionFactory = $orderCollectionFactory;

                      public function getLastestOrder()

                      /**
                      * MagentoSalesModelResourceModelOrderCollectionFactory $this->orderCollectionFactor
                      */
                      $orders = $this->orderCollectionFactory->create();
                      //Add all field to Collection
                      $orders->addFieldToSelect('*');
                      // Collection filter by Customer Id
                      $orders->addFieldToSelect('customer_id',$customerId);
                      // sort order by create date descending
                      $orders->setOrder('created_at','desc');
                      // limit collection to 1
                      $orders->setPageSize(1)->setCurPage(1);
                      if($orders->count() > 0)
                      $lastestOrder = $orders->getFirstItem();
                      return $lastestOrder;
                      else
                      // no order found
                      $lastestOrder = false;




                      `





                      share|improve this answer





























                        0














                        You can get the latest order of below code



                        • First Create an order collection.

                        • The filter that Collection by Customer ID.

                        • Sort that collection by created_at desc. setOrder('created_at', 'desc')

                        • make the collection page size 0,1 by below code using setPageSize(1),setCurPage(1)

                        `



                        <?php

                        namespace NameSpace;

                        class LastestOrder

                        /**
                        * @var MagentoSalesModelResourceModelOrderCollectionFactory
                        */
                        protected $orderCollectionFactory;

                        public function __construct(
                        MagentoSalesModelResourceModelOrderCollectionFactory $orderCollectionFactory
                        )


                        $this->orderCollectionFactory = $orderCollectionFactory;

                        public function getLastestOrder()

                        /**
                        * MagentoSalesModelResourceModelOrderCollectionFactory $this->orderCollectionFactor
                        */
                        $orders = $this->orderCollectionFactory->create();
                        //Add all field to Collection
                        $orders->addFieldToSelect('*');
                        // Collection filter by Customer Id
                        $orders->addFieldToSelect('customer_id',$customerId);
                        // sort order by create date descending
                        $orders->setOrder('created_at','desc');
                        // limit collection to 1
                        $orders->setPageSize(1)->setCurPage(1);
                        if($orders->count() > 0)
                        $lastestOrder = $orders->getFirstItem();
                        return $lastestOrder;
                        else
                        // no order found
                        $lastestOrder = false;




                        `





                        share|improve this answer



























                          0












                          0








                          0







                          You can get the latest order of below code



                          • First Create an order collection.

                          • The filter that Collection by Customer ID.

                          • Sort that collection by created_at desc. setOrder('created_at', 'desc')

                          • make the collection page size 0,1 by below code using setPageSize(1),setCurPage(1)

                          `



                          <?php

                          namespace NameSpace;

                          class LastestOrder

                          /**
                          * @var MagentoSalesModelResourceModelOrderCollectionFactory
                          */
                          protected $orderCollectionFactory;

                          public function __construct(
                          MagentoSalesModelResourceModelOrderCollectionFactory $orderCollectionFactory
                          )


                          $this->orderCollectionFactory = $orderCollectionFactory;

                          public function getLastestOrder()

                          /**
                          * MagentoSalesModelResourceModelOrderCollectionFactory $this->orderCollectionFactor
                          */
                          $orders = $this->orderCollectionFactory->create();
                          //Add all field to Collection
                          $orders->addFieldToSelect('*');
                          // Collection filter by Customer Id
                          $orders->addFieldToSelect('customer_id',$customerId);
                          // sort order by create date descending
                          $orders->setOrder('created_at','desc');
                          // limit collection to 1
                          $orders->setPageSize(1)->setCurPage(1);
                          if($orders->count() > 0)
                          $lastestOrder = $orders->getFirstItem();
                          return $lastestOrder;
                          else
                          // no order found
                          $lastestOrder = false;




                          `





                          share|improve this answer















                          You can get the latest order of below code



                          • First Create an order collection.

                          • The filter that Collection by Customer ID.

                          • Sort that collection by created_at desc. setOrder('created_at', 'desc')

                          • make the collection page size 0,1 by below code using setPageSize(1),setCurPage(1)

                          `



                          <?php

                          namespace NameSpace;

                          class LastestOrder

                          /**
                          * @var MagentoSalesModelResourceModelOrderCollectionFactory
                          */
                          protected $orderCollectionFactory;

                          public function __construct(
                          MagentoSalesModelResourceModelOrderCollectionFactory $orderCollectionFactory
                          )


                          $this->orderCollectionFactory = $orderCollectionFactory;

                          public function getLastestOrder()

                          /**
                          * MagentoSalesModelResourceModelOrderCollectionFactory $this->orderCollectionFactor
                          */
                          $orders = $this->orderCollectionFactory->create();
                          //Add all field to Collection
                          $orders->addFieldToSelect('*');
                          // Collection filter by Customer Id
                          $orders->addFieldToSelect('customer_id',$customerId);
                          // sort order by create date descending
                          $orders->setOrder('created_at','desc');
                          // limit collection to 1
                          $orders->setPageSize(1)->setCurPage(1);
                          if($orders->count() > 0)
                          $lastestOrder = $orders->getFirstItem();
                          return $lastestOrder;
                          else
                          // no order found
                          $lastestOrder = false;




                          `






                          share|improve this answer














                          share|improve this answer



                          share|improve this answer








                          edited Sep 26 '18 at 12:11

























                          answered Sep 26 '18 at 11:53









                          Amit BeraAmit Bera

                          61.7k16 gold badges84 silver badges183 bronze badges




                          61.7k16 gold badges84 silver badges183 bronze badges





















                              0














                              Use this code to get customer's last order and then any order info:



                              use MagentoSalesModelOrderRepository;
                              use MagentoFrameworkApiFilterBuilder;
                              use MagentoFrameworkApiSearchCriteriaBuilder;
                              use MagentoFrameworkApiSortOrderBuilder;

                              public function __construct(
                              OrderRepository $orderRepository,
                              SearchCriteriaBuilder $searchCriteriaBuilder,
                              FilterBuilder $filterBuilder,
                              SortOrderBuilder $sortOrderBuilder
                              )
                              $this->orderRepository = $orderRepository;
                              $this->searchCriteriaBuilder = $searchCriteriaBuilder;
                              $this->filterBuilder = $filterBuilder;
                              $this->sortOrderBuilder = $sortOrderBuilder;


                              /**
                              * @param int $customerId
                              * @return OrderSearchResultInterface
                              */
                              public function getCustomerOrders(int $customerId): OrderSearchResultInterface

                              $this->searchCriteriaBuilder->addFilter(OrderInterface::CUSTOMER_ID, $customerId);
                              $this->searchCriteriaBuilder->addFilter(OrderInterface::STATUS, ['canceled', 'holded'], 'nin');
                              $searchCriteria = $this->searchCriteriaBuilder->create();
                              $searchCriteria->setSortOrders(
                              [
                              $this->sortOrderBuilder
                              ->setField(OrderInterface::CREATED_AT)
                              ->setDirection(SortOrder::SORT_DESC)
                              ->create()
                              ]
                              );
                              $searchResults = $this->orderRepository->getList($searchCriteria);

                              return $searchResults;


                              public function getLastOrder()

                              $result = null;
                              $searchResults = $this->getCustomerOrders(<customer_id_here>);

                              if ($searchResults->getTotalCount() > 0)
                              $orders = $searchResults->getList();
                              /** @var MagentoSalesModelOrder $lastOrder */
                              $lastOrder = reset($orders);
                              $result = $lastOrder;

                              return $result;






                              share|improve this answer























                              • Donot past same content to two different questions.it creates an auto-generate duplicate flag. Please change some content to avoid this issue.

                                – Amit Bera
                                Jun 26 at 3:39















                              0














                              Use this code to get customer's last order and then any order info:



                              use MagentoSalesModelOrderRepository;
                              use MagentoFrameworkApiFilterBuilder;
                              use MagentoFrameworkApiSearchCriteriaBuilder;
                              use MagentoFrameworkApiSortOrderBuilder;

                              public function __construct(
                              OrderRepository $orderRepository,
                              SearchCriteriaBuilder $searchCriteriaBuilder,
                              FilterBuilder $filterBuilder,
                              SortOrderBuilder $sortOrderBuilder
                              )
                              $this->orderRepository = $orderRepository;
                              $this->searchCriteriaBuilder = $searchCriteriaBuilder;
                              $this->filterBuilder = $filterBuilder;
                              $this->sortOrderBuilder = $sortOrderBuilder;


                              /**
                              * @param int $customerId
                              * @return OrderSearchResultInterface
                              */
                              public function getCustomerOrders(int $customerId): OrderSearchResultInterface

                              $this->searchCriteriaBuilder->addFilter(OrderInterface::CUSTOMER_ID, $customerId);
                              $this->searchCriteriaBuilder->addFilter(OrderInterface::STATUS, ['canceled', 'holded'], 'nin');
                              $searchCriteria = $this->searchCriteriaBuilder->create();
                              $searchCriteria->setSortOrders(
                              [
                              $this->sortOrderBuilder
                              ->setField(OrderInterface::CREATED_AT)
                              ->setDirection(SortOrder::SORT_DESC)
                              ->create()
                              ]
                              );
                              $searchResults = $this->orderRepository->getList($searchCriteria);

                              return $searchResults;


                              public function getLastOrder()

                              $result = null;
                              $searchResults = $this->getCustomerOrders(<customer_id_here>);

                              if ($searchResults->getTotalCount() > 0)
                              $orders = $searchResults->getList();
                              /** @var MagentoSalesModelOrder $lastOrder */
                              $lastOrder = reset($orders);
                              $result = $lastOrder;

                              return $result;






                              share|improve this answer























                              • Donot past same content to two different questions.it creates an auto-generate duplicate flag. Please change some content to avoid this issue.

                                – Amit Bera
                                Jun 26 at 3:39













                              0












                              0








                              0







                              Use this code to get customer's last order and then any order info:



                              use MagentoSalesModelOrderRepository;
                              use MagentoFrameworkApiFilterBuilder;
                              use MagentoFrameworkApiSearchCriteriaBuilder;
                              use MagentoFrameworkApiSortOrderBuilder;

                              public function __construct(
                              OrderRepository $orderRepository,
                              SearchCriteriaBuilder $searchCriteriaBuilder,
                              FilterBuilder $filterBuilder,
                              SortOrderBuilder $sortOrderBuilder
                              )
                              $this->orderRepository = $orderRepository;
                              $this->searchCriteriaBuilder = $searchCriteriaBuilder;
                              $this->filterBuilder = $filterBuilder;
                              $this->sortOrderBuilder = $sortOrderBuilder;


                              /**
                              * @param int $customerId
                              * @return OrderSearchResultInterface
                              */
                              public function getCustomerOrders(int $customerId): OrderSearchResultInterface

                              $this->searchCriteriaBuilder->addFilter(OrderInterface::CUSTOMER_ID, $customerId);
                              $this->searchCriteriaBuilder->addFilter(OrderInterface::STATUS, ['canceled', 'holded'], 'nin');
                              $searchCriteria = $this->searchCriteriaBuilder->create();
                              $searchCriteria->setSortOrders(
                              [
                              $this->sortOrderBuilder
                              ->setField(OrderInterface::CREATED_AT)
                              ->setDirection(SortOrder::SORT_DESC)
                              ->create()
                              ]
                              );
                              $searchResults = $this->orderRepository->getList($searchCriteria);

                              return $searchResults;


                              public function getLastOrder()

                              $result = null;
                              $searchResults = $this->getCustomerOrders(<customer_id_here>);

                              if ($searchResults->getTotalCount() > 0)
                              $orders = $searchResults->getList();
                              /** @var MagentoSalesModelOrder $lastOrder */
                              $lastOrder = reset($orders);
                              $result = $lastOrder;

                              return $result;






                              share|improve this answer













                              Use this code to get customer's last order and then any order info:



                              use MagentoSalesModelOrderRepository;
                              use MagentoFrameworkApiFilterBuilder;
                              use MagentoFrameworkApiSearchCriteriaBuilder;
                              use MagentoFrameworkApiSortOrderBuilder;

                              public function __construct(
                              OrderRepository $orderRepository,
                              SearchCriteriaBuilder $searchCriteriaBuilder,
                              FilterBuilder $filterBuilder,
                              SortOrderBuilder $sortOrderBuilder
                              )
                              $this->orderRepository = $orderRepository;
                              $this->searchCriteriaBuilder = $searchCriteriaBuilder;
                              $this->filterBuilder = $filterBuilder;
                              $this->sortOrderBuilder = $sortOrderBuilder;


                              /**
                              * @param int $customerId
                              * @return OrderSearchResultInterface
                              */
                              public function getCustomerOrders(int $customerId): OrderSearchResultInterface

                              $this->searchCriteriaBuilder->addFilter(OrderInterface::CUSTOMER_ID, $customerId);
                              $this->searchCriteriaBuilder->addFilter(OrderInterface::STATUS, ['canceled', 'holded'], 'nin');
                              $searchCriteria = $this->searchCriteriaBuilder->create();
                              $searchCriteria->setSortOrders(
                              [
                              $this->sortOrderBuilder
                              ->setField(OrderInterface::CREATED_AT)
                              ->setDirection(SortOrder::SORT_DESC)
                              ->create()
                              ]
                              );
                              $searchResults = $this->orderRepository->getList($searchCriteria);

                              return $searchResults;


                              public function getLastOrder()

                              $result = null;
                              $searchResults = $this->getCustomerOrders(<customer_id_here>);

                              if ($searchResults->getTotalCount() > 0)
                              $orders = $searchResults->getList();
                              /** @var MagentoSalesModelOrder $lastOrder */
                              $lastOrder = reset($orders);
                              $result = $lastOrder;

                              return $result;







                              share|improve this answer












                              share|improve this answer



                              share|improve this answer










                              answered Jun 24 at 9:25









                              Sergey UskovSergey Uskov

                              713 bronze badges




                              713 bronze badges












                              • Donot past same content to two different questions.it creates an auto-generate duplicate flag. Please change some content to avoid this issue.

                                – Amit Bera
                                Jun 26 at 3:39

















                              • Donot past same content to two different questions.it creates an auto-generate duplicate flag. Please change some content to avoid this issue.

                                – Amit Bera
                                Jun 26 at 3:39
















                              Donot past same content to two different questions.it creates an auto-generate duplicate flag. Please change some content to avoid this issue.

                              – Amit Bera
                              Jun 26 at 3:39





                              Donot past same content to two different questions.it creates an auto-generate duplicate flag. Please change some content to avoid this issue.

                              – Amit Bera
                              Jun 26 at 3:39

















                              draft saved

                              draft discarded
















































                              Thanks for contributing an answer to Magento Stack Exchange!


                              • Please be sure to answer the question. Provide details and share your research!

                              But avoid


                              • Asking for help, clarification, or responding to other answers.

                              • Making statements based on opinion; back them up with references or personal experience.

                              To learn more, see our tips on writing great answers.




                              draft saved


                              draft discarded














                              StackExchange.ready(
                              function ()
                              StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fmagento.stackexchange.com%2fquestions%2f243900%2fget-customers-latest-order%23new-answer', 'question_page');

                              );

                              Post as a guest















                              Required, but never shown





















































                              Required, but never shown














                              Required, but never shown












                              Required, but never shown







                              Required, but never shown

































                              Required, but never shown














                              Required, but never shown












                              Required, but never shown







                              Required, but never shown







                              Popular posts from this blog

                              Grendel Contents Story Scholarship Depictions Notes References Navigation menu10.1093/notesj/gjn112Berserkeree

                              Area configuration aggregation error after install Porto themeMagento 2.1 CE Installed but front/backend not loading/workingCSS not loading on page within Magento 2 pageCannot install module in Magento 2no commands defined in the “setup” namespace. in Magento2Magento 2: Static files are present but shows 404Why do i have to always run the commands to clean cache in Magento 2.1.8?Failure reason: 'Unable to unserialize value.'Error 500 after magento migrationIn production mode the site does not loadMagento 2 : Error 500 after installing

                              Middle Expansion Olielle Resaix Definition: Uttering songs of triumph shouting with joy triumphant exulting Sejunction Journal 붙다 달 고급 품목 외출 The stretch trades the screeching tin. Definition: The act of speaking with a drawl a drawl Cough Sand Definition: An uproar a quarrel a noisy outbreak Shake Iron Publicize Horse House Baby 사과 Resaix Flaggy Jelly Temporary Unequaled Puppet A drop in the bucket Shrew 성격 회원 성질 미팅 The burn frames the tacky quality. Materialistic The smoke reduces the way. Yammoe Nondescript Cheek 얼굴 배 약하다 날리다 타다 The illegal country shows the iron. Help Rule Drearien Smoke Teaching Meaty Wasp Abraham Lincoln Jaws 진심 수리하다 Size Cork Idea Convert Think Lark John Lennon 거울 청소 군 추천하다 아이스크림