Create / Modify table without deleting data Laravel Migrate

2

I have a question about laravel regarding the Migrates. I'm using Laravel 5.1 with SQLite database.

When I run the command php artisan migrate or php artisan migrate:refresh , usually to add new tables or insert new fields to existing tables, data that previously existed is lost.

Imagine the scenario where the system already in production with several data, needs a new field in a given table. I will then have to run the php artisan migrate and the data will be lost.

My question is: Is there any way to do this database update without deleting the data from the tables?

    
asked by anonymous 11.11.2016 / 19:45

1 answer

3

When creating a migrations with the command:

php artisan make:migrations create_cars

A blank file is created with two methods: up() and down() , and inside them are written what is to be done, example :

  

Is there any way to do this update of the database without deleting the data from the tables?

Creating a migrations create_cars and within your methods:

class create_cars extends Migration
{    
    public function up()
    {
        Schema::create('cars', function (Blueprint $table) {
            $table->increments('id');
            $table->string('model', 100);
            $table->timestamp('created_at');
        });
    }

    public function down()
    {
        Schema::drop('cars');
    }
}

run the command php artisan migrate and the table with these settings and fields is created.

  

Next you want a change in the structure of this table which is the creation of a active field, but that the existing data is not lost.

Create a new migrations with the command php artisan make:migrations cars_add_active instead of Schema::create that is to create the table, put Schema::table that allows change in the structure of this table, which can be add fields, indexes, relationships and / or delete as well. In the example case a field is added in the table with the name of active , type TINYINT(4) with the default value 1 and can receive null values.

class cars_add_active extends Migration
{    
    public function up()
    {
        Schema::table('cars', function($table){
            $table->tinyInteger('active')
                ->default(1)
                ->nullable();
        });
    }

    public function down()
    {
        //
    }
}

Remembering that the existing data will never be deleted as explained in the example.

Here's all settings for columns and the explanation of how to proceed.

Note: Do not forget to install the package composer require doctrine / dbal

References:

11.11.2016 / 22:02