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

如何在Laravel migration中为json字段设置默认空数组

解决方案

你可以根据场景选择以下任意一种方案实现:

方案1:数据库迁移层面设置(推荐)

该方案在数据库层面全局生效,无论是否通过Eloquent模型操作数据库都会生效。

如果该迁移还未执行

直接修改原有迁移文件的up方法中字段定义代码即可:

public function up()
{
    Schema::table('db_invitations', function (Blueprint $table) {
        if(!Schema::hasColumn('db_invitations','interests')){
            // 新增default([])设置默认空数组
            $table->json('interests')->default([]);
        }
    });
}

如果该迁移已经执行过

不需要回滚原有迁移,新建一个字段修改迁移即可:

  1. 首先安装修改字段所需依赖:
    composer require doctrine/dbal
  2. 新建迁移文件,编写如下逻辑:
public function up()
{
    Schema::table('db_invitations', function (Blueprint $table) {
        $table->json('interests')->default([])->change();
    });
}

public function down()
{
    Schema::table('db_invitations', function (Blueprint $table) {
        $table->json('interests')->default(null)->change();
    });
}

方案2:模型层面设置

该方案仅在通过Eloquent模型创建数据时生效,无需修改数据库结构,适合不想改动已上线数据库的场景。
在模型中新增$attributes属性配置默认值即可,原有$casts配置保持不变:

/**
 * 模型属性默认值
 * @var array
 */
protected $attributes = [
    'interests' => [],
];

/**
 * The attributes that should be cast to native types.
 *
 * @var array
 */
protected $casts = [
    'interests' => 'array'
];

两种方案可同时使用,互不冲突。如果仅需Eloquent操作时默认填充,仅用方案2即可;如果需要保证所有数据库写入操作都有默认值,优先选择方案1。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.01 07:24:06