Skip to content

Instantly share code, notes, and snippets.

@fiko
Forked from Ademking/README.md
Last active April 1, 2024 15:15
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save fiko/924f6e5969585ab4ad7bef4d6d022074 to your computer and use it in GitHub Desktop.
Save fiko/924f6e5969585ab4ad7bef4d6d022074 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 :
    /**
     * @var string this attribute used to define Primary Key of the collection
     */
    protected $primaryKey = '_id';

    /**
     * Generating next/new entity id
     *
     * @return void
     */
    public function newId()
    {
        $this->{$this->primaryKey} = DB::connection(self::CONNECTION)->getCollection(self::COLLECTION)
            ->findOneAndUpdate(
                ['ref' => 'ref'],
                ['$inc' => ['seq' => 2]],
                ['new' => true, 'upsert' => true, 'returnDocument' => FindOneAndUpdate::RETURN_DOCUMENT_AFTER]
            )
            ->seq;
    }

    /**
     * method to hit event once a record is creating data
     *
     * @return void
     */
    protected static function booted(): void
    {
        static::creating(function ($model) {
            $model->newId();
        });
    }
  1. In your controller, create a new collection and use nextid() method - Example :
        $car = new Car();
	$car->newId(); // auto-increment
	$car->name = "John Doe",
        $car->save();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment