Wednesday, April 13, 2022

[FIXED] How can I modify a migration in Laravel?

Issue

I'm trying to modify a existing migration. Here is my current migration class:

class CreateLogForUserTable extends Migration
{
    public function up()
    {
        Schema::create('log_for_user', function (Blueprint $table) {
            $table->increments('id');
            $table->integer('user_id');
            $table->string('table_name');
            $table->string('error_message');
            $table->unsignedTinyInteger('error_code');
            $table->timestamps();
        });
    }

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

I've executed the php artisan migrate command once. Now I need to add ->nullable() method to the error_message column. So I edited my migration, something like this:

.
.
    $table->string('error_message')->nullable();
.
.

But when I execute php artisan migrate again, it says:

Nothing to migrate.

How can I apply the new version of the migration?


Solution

You should create a new migration using command:

php artisan make:migration update_error_message_in_log_for_user_table

Then, in that created migration class, add this line, using the change method like this:

class UpdateLogForUserTable extends Migration
{
    public function up()
    {
        Schema::table('log_for_user', function (Blueprint $table) {
            $table->string('error_message')->nullable()->change();
        });
    }

    public function down()
    {
        Schema::table('log_for_user', function (Blueprint $table) {
            $table->string('error_message')->change();
        });
    }
}

To make these changes and run the migration, use the command:

php artisan migrate

and to rollback the changes, use the command:

php artisan migrate:rollback

You may rollback a limited number of migrations by providing the step option to the rollback command. For example, the following command will rollback the last five migrations:

php artisan migrate:rollback --step=5

See more about Modifying columns with Migration



Answered By - Saumya Rastogi
Answer Checked By - Mildred Charles (PHPFixing Admin)

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.