Magento – Get the last order ID

There are many ways to get the last order ID in Magento, here is the detail:

 1. From the checkout session.

    $lastOrderId = Mage::getSingleton('checkout/session')
                   ->getLastRealOrderId();

    $orderId = Mage::getModel('sales/order')
               ->loadByIncrementId($lastOrderId)
               ->getEntityId();

This solution will not work in case you want to get the last order ID in the backend.

2. From the model.

$orders = Mage::getModel('sales/order')->getCollection()
     ->setOrder('increment_id','DESC')
     ->setPageSize(1)
     ->setCurPage(1);
$orderId = $orders->getFirstItem()->getEntityId();

This method will not work if there are multiple stores in a single Magento setup.

There is a better solution here:

$orders = Mage::getModel('sales/order')->getCollection()
     ->setOrder('created_at','DESC')
     ->setPageSize(1)
     ->setCurPage(1);

$orderId = $orders->getFirstItem()->getEntityId();

This method will work in all cases.

Hope it is useful for you 🙂

Revisions

No comments yet.

Leave a Reply