samuel toh
samuel toh

Reputation: 7076

How to change data type and add column with migration without losing data? (laravel 5.3)

My migration is like this :

public function up()
{
    Schema::create('tests', function (Blueprint $table) {
        $table->increments('id_test');
        $table->string('name', 50);
        $table->timestamps();
        $table->softDeletes();
    });
}

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

I want to change data type and add column in table test. Then update table in database. I edit like this :

public function up()
{
    Schema::create('tests', function (Blueprint $table) {
        $table->increments('id');
        $table->string('id_test', 18);
        $table->string('name', 50);
        $table->timestamps();
        $table->softDeletes();
    });
}

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

Then I run : php artisan migrate:refresh

I lost my data in database

Is there any people who can help me?

Upvotes: 2

Views: 3508

Answers (1)

kapilpatwa93
kapilpatwa93

Reputation: 4411

Create a new migration file using below command :

php artisan make:migration name_of_your_file

And its function should be like this

    public function up()
        {
            Schema::table('tests', function($table) {
                  $table->renameColumn('id_test', 'id');
                  $table->string('id_test', 18);
            });
        }


   public function down()
        {
            Schema::table('tests', function($table) {
                 $table->dropColumn('id_test');
            });
        }

Now just run below command

php artisan migrate

Note : Dont use refresh it deletes the data

To know more about Laravel Migration refer : https://laravel.com/docs/5.3/migrations#modifying-columns

Upvotes: 2

Related Questions