You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Laravel Migration如何设置字段默认值为空字符串?

修改Laravel字段默认值为空字符串的方法

嘿,这个调整其实超简单的!

你原来的代码是把reason字段默认值设为NULL:

$table->string('reason', 32)->default(NULL);

要改成默认值为空字符串(''),只需要把default()方法里的参数直接换成空字符串就行:

$table->string('reason', 32)->default('');

补充:如果是已存在的表需要修改字段

如果这个字段已经在数据库里存在了,得创建新迁移来修改它:

  1. 先生成迁移文件:
php artisan make:migration alter_reason_default_in_[your_table_name] --table=[your_table_name]

(记得把[your_table_name]替换成你实际的表名)

  1. 在生成的迁移文件里,用change()方法更新字段默认值:
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

return new class extends Migration
{
    public function up()
    {
        Schema::table('[your_table_name]', function (Blueprint $table) {
            $table->string('reason', 32)->default('')->change();
        });
    }

    public function down()
    {
        // 回滚操作,把默认值改回NULL
        Schema::table('[your_table_name]', function (Blueprint $table) {
            $table->string('reason', 32)->default(NULL)->change();
        });
    }
};
  1. 最后执行迁移:
php artisan migrate

注意:修改字段结构需要依赖doctrine/dbal扩展,如果项目还没装,先执行这个命令安装:

composer require doctrine/dbal

内容的提问来源于stack exchange,提问作者user866933

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.25 06:53:23