How to set auto-increment start in Laravel migrations?

Tutorial last revisioned on August 10, 2022 with Laravel 9
Laravel has a great database migration mechanism, but there are some things missing there. For example, what if you want your IDs start with some number, like 140001, 140002 etc? By default, we have a function increments() to set auto_increment:
Schema::create('books', function (Blueprint $table) {
    $table->increments('id');
    $table->string('name');
    // ... more fields
});
Now, there's no method or function to do something like this:
    $table->increments('id')->start_from(140000);
So we have two options here - both involve interacting with database after we create the initial schema. Option 1. Raw DB Statement After Schema::create(), just launch a raw SQL statement to change auto_increment value:
    public function up()
    {
        Schema::create('books', function (Blueprint $table) {
            $table->increments('id');
            $table->string('name');
            // ... more fields
        });

        DB::statement("ALTER TABLE books AUTO_INCREMENT = 14000;");
    }
Option 2. Insert and delete record Another feature of database is that after deleting the record, default auto_increment value still stays the same and continues from the latest number. So you can do this:
    public function up()
    {
        Schema::create('books', function (Blueprint $table) {
            $table->increments('id');
            $table->string('name');
            // ... more fields
        });

        DB::table('books')->insert(['id' => 13999, 'name' => 'whatever']);
        DB::table('books')->where('id', 13999)->delete();
    }
So, which method do you prefer? Have you done something like that in your projects? Update 2018-01-01. Our reader Gabriel Caruso tried to commit a pull request to the core framework for this. laravel auto_increment start pull request But Taylor rejected it with short answer "No plans to add right now". laravel taylor pull request Update 2022-08-10. Since Laravel 8 you can now easily change the default database auto increment value. Taylor added new method startingValue
public function up()
{
    Schema::create('posts', function (Blueprint $table) {
        $table->id()->startingValue(1200);
        ...

No comments or questions yet...

Like our articles?

Become a Premium Member for $129/year or $29/month

Recent Premium Tutorials