Easier way to run database seeders.

Submitted by kostaspt - 5 years ago

It truncates all tables and then it runs all seeders available.

// File: app/database/seeds/DatabaseSeeder.php

class DatabaseSeeder extends Seeder {

    public function run()
    {
        if (App::environment() === 'production') exit();

        Eloquent::unguard();

        // Truncate all tables, except migrations
        $tables = DB::select('SHOW TABLES');
        foreach ($tables as $table) {
            if ($table->Tables_in_database !== 'migrations')
                DB::table($table->Tables_in_database)->truncate();
        }

        // Find and run all seeders
        $classes = require base_path().'/vendor/composer/autoload_classmap.php';
        foreach ($classes as $class) {
            if (strpos($class, 'TableSeeder') !== false)
            {
                $seederClass = substr(last(explode('/', $class)), 0, -4);
                $this->call($seederClass);
            }
        }
    }
}