Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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();
});
like image 485
rits Avatar asked Nov 20 '16 10:11

rits


1 Answers

Try this:

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

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

Instead of

DB::table('products')->delete();
like image 182
Rimon Khan Avatar answered Sep 20 '22 14:09

Rimon Khan