Search code examples
laravelphpunitauto-incrementtruncatelaravel-seeding

Laravel 5.5: chow to clean/drop db data (not schema!) and reset auto-increment using seeder


I create PHPunit tests using laravel. For each test I need to "reset" DB but dropping all tables and set up schema is very slow (on mysql) - so I would like to not change schema but only delete DATA and reset AUTO-INCREMENT counters for each table.

How I can do it using seeder?


Solution

  • Because I was unable to easily find solution on net - so after my research I create seeder leave it here for future generations ;)

    use Illuminate\Database\Eloquent\Model;
    use Illuminate\Database\Seeder;
    use Illuminate\Support\Facades\DB;
    
    class CleanTablesSeeder extends Seeder
    {
        public function run()
        {
            $rows = DB::select('SHOW TABLES');
            $tables = array_column($rows, 'Tables_in_'.env('DB_DATABASE'));
    
            $this->clean($tables);
        }
    
        private function clean($tables)
        {
            Model::unguard();
            foreach ($tables as $table) {
                DB::table($table)->delete();
                DB::statement('ALTER TABLE '.$table.' AUTO_INCREMENT = 0;');
            }
        }
    }
    

    Results

    I have 22 tables in my DB (average 10 column per table), and only few seeder data for 5 tables. For calling Artisan::call(...) inside test the timing is following :

    • 17.83[s] for php artisan migrate:fresh --seed
    • 5.56[s] for php artisan db:seed (using above seder)

    As we see, seeder is more than 3x faster than setup schema from scratch - which give boost to developer who write automatic tests :)