/**
* @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();
});
}
$car = new Car();
$car->newId(); // auto-increment
$car->name = "John Doe",
$car->save();