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.
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->string('foo')->nullable(false)->change();
You must have the dbal dependency prior to running the above command:
composer require doctrine/dbal
As of Laravel 5 it's possible to reverse this by passing false as an argument to nullable
.
$table->string('foo')->nullable(false)->change();
composer require doctrine/dbal
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();
});
}
# Optional:
# public function down()
# {
# Schema::table('table_name', function ($table) {
# $table->type('column')->nullable()->change();
# });
# }
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')->nullable(false)->change();
});
}
public function down()
{
Schema::table('table_name', function ($table) {
$table->type('column')->nullable()->change();
});
}
In laravel 8, you just have to put this: "->nullable()"
$table->string('name')->nullable();
Success story sharing
$table->string('colmn', 255)->nullable()->change();
) but the reverse doesn't appear to work ($table->string('colmn', 255)->change();
), so you still need to use raw db queries for thisnullable(false)
doesn't work for me in Laravel 5.3 :(