Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Make column not nullable in a Laravel 5 migration

Tags:

sql

php

laravel-5

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.

like image 366
Juancho Ramone Avatar asked Oct 09 '15 10:10

Juancho Ramone


People also ask

How do you make an existing column foreign key in Laravel migration?

Make sure new insertions to the table will follow to add value to the column. So change your insert queries accordingly. Create a queue to update older records and run it. After the the queue finishes, convert the field into foreign key.

How do I change a column to unique in Laravel migration?

$table->unique('slug'); So you add unique index to existing 'slug'.


2 Answers

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
    });
}
like image 82
Kongxy Avatar answered Sep 20 '22 11:09

Kongxy


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(); 
    });
}
like image 40
rajangupta Avatar answered Sep 18 '22 11:09

rajangupta