Is it possible to migrate with laravel without losing the data in the tables?

1

I have my tables sent directly from laravel, but when I modify some, to add a field or remove it, at the moment of doing the migracion with laravel, I lose all the data that the tables have, there is some way to make these migrations without losing the data ?, since I did not seem to find anything about it in the official documentation.

Users Table

class CreateUsersTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('users', function (Blueprint $table) {
            $table->engine = 'InnoDB';

            $table->increments('id');
            $table->integer('role_id')->unsigned();
            $table->string('name');
            $table->string('last_name');
            $table->integer('ci')->unique();
            $table->date('birthdate');
            $table->string('email')->unique();
            $table->string('password');
            $table->rememberToken();
            $table->timestamps();

        });

        Schema::table('users', function(Blueprint $table){

            $table->foreign('role_id')->references('id')->on('roles');

        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::drop('users');
    }
}

Table Roles

class CreateRolesTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('roles', function (Blueprint $table) {
            $table->engine = 'InnoDB';

            $table->increments('id');
            $table->char('name');
            $table->timestamps();
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::drop('roles');
    }
}
    
asked by Edwin Aquino 18.05.2018 в 19:43
source

1 answer

3

The correct thing in this case is to create a new migration to modify the table, for example, add a "hobby" field in the users table:

class AddHobbyFieldUsersTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::table('users', function (Blueprint $table) {

            $table->string('hobby')->nullable();

        });

    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::table('users', function (Blueprint $table) {
            $table->dropColumn('hobby');
        });
    }
}

Once the new migration is created, you execute it and do not lose any existing value in the table, however it is always mandatory to backup before a migration.

    
answered by 18.05.2018 / 19:51
source