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

Laravel中JSON字段无法接收其他列值,如何修改表单实现数据收集?

问题解决步骤

1. 先修复数据库字段的默认值错误

你遇到的SQLSTATE[HY000]: General error: 1364 Field 'properties' doesn't have a default value错误,是因为数据库里的properties字段没设默认值,且创建记录时没给这个字段传值。

修改迁移文件(如果是已运行过的迁移,建议新建迁移修改字段),给properties添加默认空JSON:

// 原迁移文件修改properties字段定义
$table->json('properties')->default(json_encode([]));

如果是已执行的迁移,新建一个字段修改迁移:

public function up()
{
    Schema::table('hunters', function (Blueprint $table) {
        $table->json('properties')->default(json_encode([]))->change();
    });
}

执行迁移命令让修改生效:

php artisan migrate

2. 实现properties收集其他列数据的逻辑

你的表单不需要修改现有输入控件,要收集的是已经提交的字段值,只需要在后端处理请求数据:

修改HunterController.php的store方法:

public function store(HunterRequest $request)
{
    $validations = $request->validated();
    
    // 定义要存入properties的目标字段列表
    $targetFields = [
        'name_hunter',
        'year_hunter',
        'height_hunter',
        'weight_hunter',
        'type_hunter',
        'type_nen',
        'type_sangue'
    ];
    
    // 筛选出目标字段的值,存入properties
    $validations['properties'] = array_intersect_key($validations, array_flip($targetFields));
    
    HunterModel::create($validations);
    return redirect('/');   
}

3. 配置模型批量赋值权限

在HunterModel.php里把properties加入$fillable,允许批量赋值操作:

protected $fillable = [
    'name_hunter',
    'year_hunter',
    'height_hunter',
    'weight_hunter',
    'type_hunter',
    'type_nen',
    'type_sangue',
    'properties'
];

表单说明

你当前的表单已经能正确提交所有需要的字段,不需要做任何输入控件的修改。如果后续要动态添加额外字段到properties,可以在表单里添加隐藏字段或动态生成的输入框,但当前需求下现有表单完全够用。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.12 05:25:12