How to reset auto increment in laravel user deletion?

Viewed 35749

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..

4 Answers
use Illuminate\Support\Facades\DB;

public function refreshDB()
{
    $max = DB::table('users')->max('id') + 1; 
    DB::statement("ALTER TABLE users AUTO_INCREMENT =  $max");
}

// Note: This solution is for resetting the auto_increment of the table without truncating the table itself 

If you are using PostgreSQL:

public function resetAutoincrement()
{
    $max = DB::table('users')->max('id') + 1;
    DB::statement('ALTER SEQUENCE users_id_seq RESTART WITH ' . $max);
}
Related