Reputation: 482
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();
});
}
Upvotes: 6
Views: 11954
Reputation: 3
Use this line after Schema::create
DB::statement('ALTER TABLE users AUTO_INCREMENT = 1000;');
Upvotes: 0
Reputation: 1247
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();
});
}
Upvotes: 2
Reputation: 303
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
Upvotes: 14
Reputation: 825
After Creating Migrations Just Go to your Mysql Database and put this query
ALTER TABLE users AUTO_INCREMENT = 1000;
Upvotes: 0
Reputation: 89
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
Upvotes: 1
Reputation: 4992
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
Upvotes: 2