2
class UpdateSessions extends Migration {

    public function up()
    {
            Schema::table('sessions', function($table){
                $table->string('comCode')->nullable()->change();
            });
    }

    public function down()
    {
         // What should i write here?
    }

}

I have already created a sessions table writing a migration to change the column to be nullable. Now i am confused on what should i write in down?

Konrad Krakowiak
  • 12,285
  • 11
  • 58
  • 45
Ali Shaukat
  • 935
  • 6
  • 20

2 Answers2

3

In the down method of a migration, you undo the changes you made within the up method. This method is called when you rollaback a migration with the artisan migrate:rollback command. In your case it would look something like this:

public function down()
{
    // Laravel doesn't have a method to undo ->nullable()
    // so you have to do use a raw query in this case
    DB::statement('ALTER TABLE sessions MODIFY comCode VARCHAR(255) NOT NULL');
}

So if in your migration up you modified the column named comCode to be nullable, when rolling back the migration you'd need to update that column definition to make it not null, and that's what you do in the down method.

It's not necessary to have anything in the down method in order for the migration to run successfully, however once the migration is ran you won't be able to roll it back unless you have the correct code in the down method.

Bogdan
  • 43,166
  • 12
  • 128
  • 129
  • is it a good practice to revert the change using DB:statement? i have portability in my mind. this statement might work for mysql but not work for all dbms? – Ali Shaukat Feb 26 '15 at 10:35
  • @alishaukat No, it's not a good practice, and should be avoided whenever possible. However in this case it was necessary, because there was no method available to abstract the query needed for this change. Most DBMSs require a complete definition of the column to alter it, and since the Schema Builder is oblivious to the column definition set in previous migrations, you'll need to specify them all again when applying the change (and that can have many implications because you might need to also redefine keys and constraints). – Bogdan Feb 26 '15 at 10:55
  • There a lengthy discussion on this particular column update problem [here](https://github.com/laravel/framework/issues/895), but there seems to be no solution in sight. – Bogdan Feb 26 '15 at 11:02
  • What happens if there is a null data in db ? He insert data after migrate with null values. And you try to remove nullable in down method.. Its crashed. – Mustafa Acar Jan 24 '22 at 15:16
2

As of now Dec 2015, at least with Laravel 5 you can just write

Schema::table('sessions', function($table){
    $table->string('comCode')->change();
});

Note: this time there is no nullable()

karmendra
  • 2,206
  • 8
  • 31
  • 49