create migration from SQL dump file Laravel 1024x548 1
| | |

How to create migration from SQL dump in Laravel

Find out how to use Laravel migrations to construct migrations using SQL dump files. Use the DB::unprepared(() function when migrating a Laravel import SQL file dump.

If I were to remodel an existing project, I’d build migrations from scratch, import the dump into separate tables (or a different database, if the table names are the same), and then import the content to the new structure using seeds.

SQL dump path with DB::unprepared()

DB::unprepared(file_get_contents(database_path('data/countries.sql');

// or

DB::unprepared(file_get_contents('full/path/to/countries.sql'));

Create migration from SQL dump in up() method

create migration from SQL dump file Laravel 1024x548 1
<?php


use Illuminate\Database\Migrations\Migration;
use Illuminate\Support\Facades\DB;


return new class extends Migration {
	/**
	* Run the migrations.
	*
	* @return void
	*/
	public function up() {
		// Create tables with prerequisite data
		DB::unprepared(file_get_contents(database_path('data/countries.sql');
		DB::unprepared(file_get_contents(database_path('data/states.sql');
		DB::unprepared(file_get_contents(database_path('data/cities.sql');
		DB::unprepared(file_get_contents(database_path('data/zipcodes.sql');
		DB::unprepared(file_get_contents(database_path('data/languages.sql');
		DB::unprepared(file_get_contents(database_path('data/timezones.sql');
		DB::unprepared(file_get_contents(database_path('data/currencies.sql');
	}

	/**
	* Reverse the migrations.
	*
	* @return void
	*/
	public function down()
	{
		// Drop tables
		Schema::dropIfExists('currencies');
		Schema::dropIfExists('timezones');
		Schema::dropIfExists('languages');
		Schema::dropIfExists('zipcodes');
		Schema::dropIfExists('cities');
		Schema::dropIfExists('states');
		Schema::dropIfExists('countries');
	}
}

Drop migration tables in down() method

create migration from mysql dump Laravel

51 / 100

Similar Posts

Leave a Reply

Your email address will not be published. Required fields are marked *