laravel

Can I import a mysql dump to a laravel migration?


I have a complete database and need to create migration. I guess there must be a way to do it from a dump but not sure. Is there any way automatically or at least easier to do this task?


Solution

  • If you can dump to a CSV: An alternative for some generic data tables (Countries, States, Postal Codes), not via migrations but via seeders. Although you could do it the same way in a migration file.

    In your seeder file:

        public function run()
        {
            $this->insertFromCsvFile('countries', 'path/to/countries.csv');
            $this->insertFromCsvFile('states', 'path/to/states.csv');
            $this->insertFromCsvFile('postal_codes', 'path/to/postal_codes.csv');
        }
    
        private function insertFromCsvFile($tableName, $filePath)
        {
            if( !file_exists($filePath) ){
                echo 'File Not Found: '.$filePath."\r\n";
                return;
            }
            $headers = $rows = [];
            $file = fopen( $filePath, 'r' );
            while( ( $line = fgetcsv( $file ) ) !== false ){
    
                // The first row should be header values that match column names.
                if( empty( $headers ) ){
                    $headers = explode( ',', implode( ',', $line ) );
                    continue;
                }
    
                $row = array_combine( $headers, $line );
                foreach( $row as &$val ) if( $val === 'NULL' ) $val = null;
                $rows[] = $row;
    
                // Adjust based on memory constraints.
                if( count($rows) === 500 ){
                    DB::table( $tableName )->insert($rows);
                    $rows = [];
                }
            }
            fclose( $filePath );
    
            if( count($rows) ) DB::table( $tableName )->insert($rows);
        }
    

    Run the seeder: php artisan db:seed --class=GenericTableSeeder