Norway


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?

The post How to set auto-increment start in Laravel migrations? appeared first on Laravel Daily.



Source link

No tags for this post.

LEAVE A REPLY

Please enter your comment!
Please enter your name here