Jakub Kohout
Jakub Kohout

Reputation: 1944

Laravel seeder sets first record with ID 2

I am trying to seed my database via DatabaseSeeder Laravel, but when it seeds the database, the first row has ID 2 instead of 1.

DatabaseSeeder.php

public function run()
{

    foreach ($this->to_truncate as $table) {
        DB::table($table)->truncate();
    }

  $this->call('UsersTableSeeder');
}

UsersTableSeeder.php

use Illuminate\Database\Seeder;

class UsersTableSeeder extends Seeder
{
    public function run()
    {
        factory('App\User', 1)->create();
    }
}

ModelFactory.php

$factory->define(App\User::class, function (Faker\Generator $faker) {
    return [
        'full_name' => 'Jakub Kohout',
        'username' => 'Admin',
        'email' => '[email protected]',
        'password' => bcrypt('Uchiha'),
        'role_id' => 1
    ];
});

My seeding process looks like this:

heroku run php artisan migrate
heroku run php artisan db:seed

This is the migration for my User model:

public function up()
{
    Schema::create('users', function (Blueprint $table) {
        $table->increments('id');
        $table->string('username');
        $table->string('email')->unique();
        $table->string('full_name');
        $table->integer('role_id')->unsigned();
        $table->string('password', 60);
        $table->rememberToken();
        $table->timestamps();
    });
}

Upvotes: 1

Views: 2177

Answers (2)

Nemanja Martinovic
Nemanja Martinovic

Reputation: 183

I'll presume that you are using MySQL - if so you can run following command:

SHOW VARIABLES LIKE 'auto_inc%';

and it should return something like:

+--------------------------+-------+
| Variable_name            | Value |
+--------------------------+-------+
| auto_increment_increment | 10    |
| auto_increment_offset    | 2     |
+--------------------------+-------+

Offset is whats giving you headaches. Both of this can be set by running (from within MySQL):

SET @@auto_increment_increment=1;
SET @@auto_increment_offset=1;

Upvotes: 1

Gouda Elalfy
Gouda Elalfy

Reputation: 7023

if your ID is auto incremental and you put 1 row before then delete it, then the second row ID will be 2, it is mysql not laravel. and you can solve this issue by dropping table then create it again with auto increment begin with 1.

or you can this query:

ALTER TABLE tablename AUTO_INCREMENT = 1

Upvotes: 2

Related Questions