I am trying to replace default order/invoice number sequence in magento2. I have completed successfully by using following code.

di.xml file

<?xml version='1.0'?>
    <type name='Magento\SalesSequence\Model\Manager'>
        <plugin name='Test\SalesSequence\Plugin\Model\Manager' type='Test\SalesSequence\Plugin\Model\Manager'/>

Manager.php file

namespace Test\SalesSequence\Plugin\Model;

use Magento\SalesSequence\Model\Manager as Sb;
use Magento\SalesSequence\Model\Sequence as Sequence;
use Magento\Framework\App\ResourceConnection as AppResource;
use Magento\Framework\EntityManager\Sequence\SequenceFactory as SequenceFactory;
use Magento\SalesSequence\Model\ResourceModel\Meta as ResourceSequenceMeta;

class Manager extends Sb {

    protected $checkoutSession;

    private $storeId;

    private $type;

    protected $sequenceFactory;

    protected $resourceSequenceMeta;

    public function __construct(
        \Magento\Checkout\Model\Session $checkoutSession,
        SequenceFactory $sequenceFactory,
        ResourceSequenceMeta $resourceSequenceMeta
    ) {
        $this->checkoutSession = $checkoutSession;
        $this->sequenceFactory = $sequenceFactory;
        $this->resourceSequenceMeta = $resourceSequenceMeta;

    public function aroundGetSequence(Sb $sb, \Closure $f, $entityType, $storeId) 
        return $this->saleSeq(Sequence::class, [
            'meta' => $this->saleSeqMeta($entityType, $storeId), 'pattern' => $this->pattern()

    private function pattern() 
        //last order id.
        $lastCreatedOrderNumber  = $this->checkoutSession->getLastRealOrderId();

        //last order created day
        $orderCreatedAt = $this->checkoutSession->getLastRealOrder()->getCreatedAt();


I don't want to use $this->checkoutSession to get last order id from the database.

I want to get the last order id placed in the store.

Is there anyway, I can get last order id here?


We can use \Magento\Sales\Model\ResourceModel\Order\Grid\Collection instead of CheckoutSession to get last order for a specific store.

This collection is basically being used to populate order data in sales order grid in Admin Panel and we can filter this collection by created_at field to get the last placed order as below.

class LastOrder
    protected $orderGridCollection;

    public function __construct(
        \Magento\Sales\Model\ResourceModel\Order\Grid\Collection $collection
    ) {
        $this->orderGridCollection = $collection;

    public function getLastOrder($storeId)
        $lastOrderData = $this->orderGridCollection
            ->addFieldToFilter('store_id', array('eq' => $storeId))


Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.