Emil Emil - 15 days ago 14
MySQL Question

Laravel: Reset auto increment before re-seeding a table

Is there a way to set auto increment back to 1 before seeding a table?

I empty the table before seeding it and if I didn't do

migrate:refresh
before seeding it then it continues the auto increment of the ID from the last position, e.g., 4.

Table seed:

public function run()
{
DB::table('products')->delete();
// Product table seeder
$product = new \App\Product([
'category_id' => 1,
'image_path' => '/images/products/1/000001.jpg',
'title' => 'test',
]);
$product->save();
}


Creating the table:

Schema::create('products', function (Blueprint $table) {
$table->increments('id');
$table->integer('category_id')->unsigned();
$table->foreign('category_id')->references('id')->on('categories');
$table->string('image_path');
$table->string('title');
$table->timestamps();
});

Answer

Try this:

DB::statement('SET FOREIGN_KEY_CHECKS=0');

DB::table('products')->truncate();

Instead of

DB::table('products')->delete();
Comments