Skip to content

Instantly share code, notes, and snippets.

@Ademking
Created May 28, 2019 04:39
Show Gist options
  • Star 4 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save Ademking/ef99bb8abf04afda6baabd5fc5d22659 to your computer and use it in GitHub Desktop.
Save Ademking/ef99bb8abf04afda6baabd5fc5d22659 to your computer and use it in GitHub Desktop.
Laravel How to use Auto Increment with MongoDB (jenssegers)
  1. In your model, add these methods :
    public function nextid()
    {
        // ref is the counter - change it to whatever you want to increment
        $this->ref = self::getID();
    }

    public static function bootUseAutoIncrementID()
    {
        static::creating(function ($model) {
            $model->sequencial_id = self::getID($model->getTable());
        });
    }
    public function getCasts()
    {
        return $this->casts;
    }
    
    private static function getID()
    {
        $seq = DB::connection('mongodb')->getCollection('counters')->findOneAndUpdate(
            ['ref' => 'ref'],
            ['$inc' => ['seq' => 1]],
            ['new' => true, 'upsert' => true, 'returnDocument' => FindOneAndUpdate::RETURN_DOCUMENT_AFTER]
        );
        return $seq->seq;
    }
  1. In your controller, create a new collection and use nextid() method - Example :
        $car = new Car();
	$car->nextid(); // auto-increment
	$car->name = "Ferrari",
        $car->save();
@markhacd
Copy link

markhacd commented Aug 21, 2019

Thanks, It's Works

@mmoghadam11
Copy link

mmoghadam11 commented Aug 28, 2022

in Model create methode how can we use this???

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment