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 did it this way:
$user = User::find($user_id);
if ($user) {
if ($user->delete()){
DB::statement('ALTER TABLE users AUTO_INCREMENT = '.(count(User::all())+1).';');
echo json_encode('User Was Deleted Successfully..');
}
}
each time i delete a user from the database i set the auto increment pointer to the number of all users +1.
if anybody has a better solution inform me please..
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 hasForeign Key Constraints
applied on it (truncate
is not the same asdelete
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 hasforeign 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 atapp/database/seeds/DatabaseSeeder.php
) as follows:Now the Table Seeder classes (Example,
UserTableSeeder
in this case, which should be created atapp/database/seeds/UserTableSeeder.php
) can call truncate table(s) as follows:I don't know if it's smart or not, but this will cleanup your table.
MySQL will set the AUTO_INCREMENT to last+1
If you've set your foreign keys to ON UPDATE CASCADE the children will know about the changes and cascade the update.
This stuff takes server time and gives you little in return. I think that's why you're getting loads of "don't waist your time" responses? For a count you should use ->count() and not the last id.
I also don't know if the statements should be within a transaction to prevent errors when users are added while your statements are running.