How to disable Laravel eloquent Auto Increment?

Viewed 45638

I need an effective way to disable Laravel from auto incriminating the primary key of the table which I am going to insert data in.

Why? I don't check if there is any duplication between the DB and the inserted data so if there was any duplication I just handles it in a try-catch block.

The problem is if there was any failure Laravel counts it like I have inserted a row. So IDs column is not going to be in this order [1, 2, 3, etc], but in this [1, 4, 8, 20, etc].

I searched a lot about this issue and I have tried to use this line after the declaration of the class:

public $autoincrement = false;

Also

public $incrementing = false;

But they are not working.

I just want to use the AI of my DB. Not Laravel's one.

9 Answers

In your model:

public $incrementing = false;

In your migration:

//Remove the default $table->id();

//second param is what auto-increments, default is false so can be skipped
$table->unsignedBigInteger('id', false)->primary(); 

A quick comment on all the other outdated or wrong solutions you see here:

  • $primaryKey does not need to be overridden unless the primary column is different than 'id'
  • You do not need to use the ugly DB transaction just to remove auto-incrementing! Keep using the lovely eloquent models and just use this answer.

You can use

public function up()
{
    Schema::create('users', function (Blueprint $table) {
        $table->integer('matricule')->unsigned();;
        $table->primary(['matricule']);
        $table->string('nometprenom');
        $table->string('age');
        $table->string('adresse');
        $table->string('telephone');
        $table->string('login');
        $table->string('password');
        $table->string('type');
        $table->engine = 'InnoDB';
        
    });
}
Related