I have been struggling to find out a way to reset the auto increment value in Laravel 4 but it seems that this functionality is not embedded in laravel 4 at least for now. so i
Like everyone else replied, there is not really a need to move the counter back when you delete a row. You can however truncate
a table which will delete all the table rows and reset the counter.
You cannot truncate
a table that has Foreign Key Constraints
applied on it (truncate
is not the same as delete
which simply deletes all the rows while keeping the auto-increment counter.).
Hence, while using foreign key constrains
, MySQL might stop you from truncating a table which has foreign key constraints
applied to it.
You can perform the following steps to achieve what you want, but beware, there may be a risk to your data integrity. I only use it for my testing purposes.
Edit the DatabaseSeeder
class (which is available at app/database/seeds/DatabaseSeeder.php
) as follows:
call('UserTableSeeder');
// ...
// FOREIGN_KEY_CHECKS is supposed to only apply to a single
// connection and reset itself but I like to explicitly
// undo what I've done for clarity
DB::statement('SET FOREIGN_KEY_CHECKS=1;');
}
}
Now the Table Seeder classes (Example, UserTableSeeder
in this case, which should be created at app/database/seeds/UserTableSeeder.php
) can call truncate table(s) as follows:
truncate();
// The auto-increment has been reset.
// Now we can start adding users.
User::create(
array(
'email' => 'example@domain.com',
'password' => Hash::make('test')
)
);
}
}