Home > OS >  How can I modify DB structure in Laravel without truncating tables?
How can I modify DB structure in Laravel without truncating tables?

Time:01-05

I have defined a DB table structure below.

If I want to modify a table column:

From

$table->string('active',1);

To:

$table->string('active',1)->nullable(); // allow null values

Every time I run the migration script, my tables will be truncated.

Is there a way to define a table structure and have it be modified to correct structure WITHOUT dropping the table?

Here is my code for now:

<?php

use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;

class VTUser extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('Z_user', function (Blueprint $table) {
            $table->bigIncrements('id');
            $table->string('nickname')->unique();
            $table->string('email')->unique();
            $table->string('passhash');
            $table->string('keygen');
            $table->string('active',1)->nullable();
            $table->string('banned',1);
            $table->string('admin',1);
            $table->string('step',1);

            // $table->rememberToken();
            // $table->timestamps();
        });
    }

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

CodePudding user response:

Try...

public function up()
{
    Schema::table('Z_user', function (Blueprint $table) {
        $table->string('active',1)->nullable()->change();
    });
}

CodePudding user response:

There can be two ways of achieving this -

  1. Either you can rollback the migration with php artisan migrate:rollback --step=1 and then change the up function with $table->string('active',1)->nullable();

  2. Create a new migration to update the table by doing $table->string('active',1)->nullable(); in this new migration.

  • Related