Google+

Pages

Wednesday, August 8, 2012

Magento: How to get last order id

There are many ways to get last order id:
 
1.  From checkout session:

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

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


Above solution will not work, if you want to get last order id in admin.
For this you can try this solution:

2.  From model:
 

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


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

But this method will not work, if there are multi store in a single magento setup. So a better solution would be:

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

$orderId = $orders->getFirstItem()->getEntityId();
 
 
That's all.. Enjoy.. :) 

8 comments:

Anonymous said...

Thanks for the post. Good Job.

Keep it up.. :)

Anonymous said...

Please tell me In which Folder Should I Paste this Code?

MOHIT KUMAR ARORA said...

Thanks for your query..

You can paste it in file you want to get order id. It is up to your requirement.

Let me know if you have any problem regarding my answer.

Anonymous said...

I am not getting you In which folder should I paste it?

MOHIT KUMAR ARORA said...

On which page you are trying to get last order id.

example: Order Success page/ category listing page etc??

Supose you are trying to get last order id on Order Success page, you can use below file to paste your code:

app/design/frontend/[your package]/[your theme]/template/checkout/success.phtml

Let me know if you want to get it on other page.

Mihai Ilie said...

Thank's for your good job!

Ajit said...

Good Job!!!!!!!!!!

Felipe said...

Amigo, essa sua solução salvou meu dia, obrigado;