I'm writing a migration to make certain columns in a table nullable right now. For the down function, I of course want to make those columns not nullable again. I looked through the schema builder docs, but couldn't see a way to do this.

Any help would be appreciated.

4 Answers 正确答案 

up vote142down voteaccepted

Prior to Laravel 5 there was no Laravel native way of altering an existing table column using the schema builder. You'd need to use raw queries for this.

However, as of Laravel 5 you can use:

$table->...->nullable(false)->change();


/**
 * 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
    });
}

As of Laravel 5, it's possible to reverse this natively - simply pass false as an argument to nullable().

e.g.

$table -> string('foo') -> nullable(false) -> change();

First run this:

composer require doctrine/dbal

Then create a migration that will alter the table like so:

php artisan make:migration fix_whatever_table_name_here

public function up()
{
    Schema::table('table_name', function (Blueprint $table) {
        $table->type('column')->nullable(false)->change();
    });
}

public function down()
{
    Schema::table('table_name', function ($table) {
        $table->dropColumn('column');
    });
}

the below information is for SQL
Use the below code first

UPDATE [Table] SET [Column]=0 WHERE [Column] IS NULL

than run this code

ALTER TABLE [Table] MODIFY [Column] INTEGER NOT NULL

来自  https://stackoverflow.com/questions/14013832/make-column-not-nullable-in-a-laravel-migration