Make column not nullable in a Laravel migration

前端 未结 4 726
醉酒成梦
醉酒成梦 2020-12-12 17:32

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

相关标签:
4条回答
  • 2020-12-12 18:14

    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');
    #     });
    # }
    
    0 讨论(0)
  • 2020-12-12 18:17

    You can just declare the column again without ->nullable() and use ->change

    public function up()
    {
        Schema::table('table_name', function (Blueprint $table) {
            $table->type('column')->change();
        });
    }
    
    public function down()
    {
        Schema::table('table_name', function ($table) {
            $table->type('column')->nullable()->change();
        });
    }
    
    0 讨论(0)
  • 2020-12-12 18:20

    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();
    
    0 讨论(0)
  • 2020-12-12 18:28

    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();
    
    0 讨论(0)
提交回复
热议问题