1

I need auto generate id sequence.

I am using jenssegers.

I have a UseAutoIncrementID trait from here.

And using it as:

use App\Traits\UseAutoIncrementID;
....
....
$data['_id'] = $this->getID('request_feeds'); // request_feeds is collection name.

I get this error:

(1/1) FatalThrowableError
Call to undefined method Illuminate\Database\MySqlConnection::getCollection()

How can I get auto generated id sequence with jenssegers?

Azima
  • 3,835
  • 15
  • 49
  • 95

1 Answers1

0
  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();
Adem Kouki
  • 17
  • 1
  • 3