Create/Modify table without deleting data Laravel Migrate

Asked

Viewed 8,769 times

2

I have a question about the Migrates. I am using Laravel 5.1 with Sqlite database.

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

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

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

  • You have the migrations that for example adds fields in an existing table?

1 answer

5


When you create a Migrations by command:

php artisan make:migrations create_cars

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


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

Creating a Migrations create_cars and within their ways:

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 is created with these settings and fields.

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

Create a new Migrations with the command php artisan make:migrations cars_add_active and instead of Schema::create which is to create the table, put Schema::table which allows changes 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, of the kind TINYINT(4) with the default value 1 and can receive values null.

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 existing data will never be deleted as explained in the example.

There are all the column settings and how to proceed.

Observing: don’t forget to install the package composer require Doctrine/dbal

References:

Browser other questions tagged

You are not signed in. Login or sign up in order to post.