4

I want to write a Laravel Migration auto increment ID as a primary key. I want to start this ID with a another value rather than 1. How can I do so ?

The migration up() function:

public function up()
{
    Schema::create('users', function (Blueprint $table) {
        $table->bigIncrements('id');
        $table->string('name');
        $table->string('email')->unique();
        $table->string('phone');
        $table->rememberToken();
        $table->timestamps();
    });
}
Yomna Hesham
  • 462
  • 3
  • 16
  • I don't think there's an elegant way to do this. You'll probably need to run a raw db statement via `DB::statement(..)` and use one of the solutions at https://stackoverflow.com/questions/1485668/how-to-set-initial-value-and-auto-increment-in-mysql – apokryfos Feb 03 '20 at 14:46

6 Answers6

10

As of Laravel 8.x, you can now use this in your migration:

public function up()
{
    Schema::create('posts', function (Blueprint $table) {
        $table->id()->startingValue(1200);
    });
}

Source: https://laravel-news.com/laravel-auto-increment

Brent Arcane
  • 163
  • 2
  • 8
2

You can use 2 methods

By Statement DB::statement("ALTER TABLE your_table_here SET AUTO_INCREMENT = 9999;");

By inserting row and deleteing it.

DB::table('your_table_here ')->insert(['id' => 99999, ... ,'column' => 'value']);
DB::table('your_table_here ')->where('id', 99999)->delete();

Hope this helps

Malkhazi Dartsmelidze
  • 4,783
  • 4
  • 16
  • 40
1

If you want your first ID in the table to be for example 10001.

If you are using Laravel 8.x

public function up()
{
    Schema::create('users', function (Blueprint $table) {
        $table->bigIncrements('id')->from(10001);
        .
        .
        $table->timestamps();
    });
}
Prateek
  • 1,229
  • 17
  • 31
0

add a record with id (desired id -1) and then delete it.

If you add a record with id 999, and then delete it, next record will have id 1000. You can also use SQL identity on your database

Yomna Hesham
  • 462
  • 3
  • 16
Filip
  • 79
  • 6
0

After Creating Migrations Just Go to your Mysql Database and put this query

ALTER TABLE users AUTO_INCREMENT = 1000;
Naeem Ijaz
  • 805
  • 9
  • 17
-3

try this ?

$table->increments('id')->start_from(10000);
feivorid
  • 1
  • 2
  • 1
    that method doesn't exist, not even in Version 6.0 https://laraveldaily.com/set-auto-increment-start-laravel-migrations/ – Edwin Krause Feb 03 '20 at 15:05