12

I have found this question very similar to mine Make column not nullable in a Laravel migration though it is almost 3 years old and it surely does not belong to Laravel 5

My problem is that I have a migration which in the up function it modifies a column to make it nullable. Now, in the down function I want to make it not nullable again.

/**
 * Run the migrations.
 *
 * @return void
 */
public function up()
{
    Schema::table('mytable', function(Blueprint $table) {
        $table->string('mycolumn')->nullable()->change();
    });
}

/**
 * Reverse the migrations.
 *
 * @return void
 */
public function down()
{
    Schema::table('mytable', function(Blueprint $table) {
    /* THIS IS WHAT I WOULD EXPECT TO DO
    THOUGH OF COURSE THE FUNCTION notNullable DOES NOT WORK */
        $table->string('mycolumn')->notNullable()->change(); 
    });
}

I could achieve that using raw SQL, but I would like to do it using Laravel methods if it is possible... but I couldn't find it, probably it hasn't been implemented it in the version 5 either.

Community
  • 1
  • 1
Juan Girini
  • 1,150
  • 2
  • 16
  • 31

2 Answers2

29

To reset it back to not nullable. You may try this.

/**
 * Run the migrations.
 *
 * @return void
 */
public function up()
{
    Schema::table('mytable', function(Blueprint $table) {
        $table->string('mycolumn')->nullable()->change();
    });
}

/**
 * Reverse the migrations.
 *
 * @return void
 */
public function down()
{
    Schema::table('mytable', function(Blueprint $table) {
    /* By default it's NOT NULL */
        $table->string('mycolumn')->nullable(false)->change(); // <--- here
    });
}
Kongxy
  • 406
  • 4
  • 5
  • 2
    I think this constraint will not work because you allowed nullable in your column. So when you will rollback, if one of your db line has a null value in that column (as you allowed it) , when you will rollback it will try to make the field not nullable, but it will fail as some values are null . – ybert Jun 25 '19 at 15:29
1

By default its NOT NULL, so you should try this.

/**
 * Run the migrations.
 *
 * @return void
 */
public function up()
{
    Schema::table('mytable', function(Blueprint $table) {
        $table->string('mycolumn')->nullable()->change();
    });
}

/**
 * Reverse the migrations.
 *
 * @return void
 */
public function down()
{
    Schema::table('mytable', function(Blueprint $table) {
    /* By default it's NOT NULL */
        $table->string('mycolumn')->change(); 
    });
}
rajangupta
  • 329
  • 2
  • 8
  • 15
  • 1
    I also thought this might work but unfortunately it does not return to its default – Juan Girini Oct 10 '15 at 16:01
  • Nice thought but Does not work in Laravel 5.7 either - just to save others time, $table->unsignedInteger('foreign_id')->change(); does NOT revert the column back to being required (non-nullable). – NULL pointer Oct 03 '18 at 23:27