Braike dp
Braike dp

Reputation: 226

How to add a nullable column type to an already migrated table

I have a migration with $table->datetime('published_at'); and it is already migrated and data is filled in. Now, I have to make this column ->nullable(), but without using migrate:refresh or rollback. How can I achieve this or is it even possible.

Note: No raw sql queries or phpmyadmin. Looking for migration methods.

Upvotes: 0

Views: 62

Answers (3)

Tim Lewis
Tim Lewis

Reputation: 29258

You can create a new migration:

php artisan make:migration change_published_at_to_nullable

This will generate a new Migration file called

XXXX_YYY_ZZZ_000000_change_published_at_to_nullable.php

In this migration file, add the following code:

public function up(){
  Schema::table("table", function (Blueprint $table) {
    $table->string("published_at")->nullable()->change();
  });
}

public function down(){
  Schema::table("table", function (Blueprint $table) {
    $table->string("published_at")->nullable(false)->change();
  });
}

When the command php artisan migrate is run, the published_at column will be changed to allow null. If you need to reverse this, php artisan migrate:refresh, or php artisan migrate:reset, or php artisan migrate:rollback --step will change the column back to allow not null.

Upvotes: 1

Mohammad Hosseini
Mohammad Hosseini

Reputation: 1797

create new migration and add code below:

Schema::table('table_name', function (Blueprint $table) {
    $table->string('published_at')->nullable()->change();
});

or if using mysql:

You can change your table's structure directly in phpmyadmin

Go to phpmyadmin -> table -> structure

edit publishd_at column and tick null

Upvotes: 1

Lulceltech
Lulceltech

Reputation: 1702

Simple way is to just run a query like this:

ALTER TABLE my_table MODIFY published_at DATETIME NULL

Upvotes: -1

Related Questions