Data migration from old table into new table, with Laravel 4
database-migration, laravel, laravel-4, migration, php
Solution
Thanks to suggestion from @TonyArra and @Fractaliste, we now do something like following, this allow us to test run migration and rollback without worrying about data lost.
use Illuminate\Database\Migrations\Migration;
use MyNewModel;
class DataConvert extends Migration {
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
foreach(MyOldModel::all() as $item)
{
MyNewModel::create(array(...));
}
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
MyNewModel::truncate();
}
}
Problem
Is it possible to copy data from old table into new table instead of `rename`? We are planning a major database schema upgrade and would like to preserve current data tables, so the migration `down()` can be as simple as dropping newly created tables. we realize this breaks backward compatibility as `migrate:rollback` doesn't really rollback any new data into previous state; but enabling such thing will be very costly due to the scale of schema update, we are content with a simple 1-way migration, as long as it preserves old tables. Can this be done within Laravel's migration and schema alone?