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

Laravel动态表单数组存储报错:htmlspecialchars参数类型错误求助

解决Laravel动态表单数组提交时的类型不匹配错误

你遇到的htmlspecialchars()类型错误,核心原因是控制器中直接将整个competency_point、grade、predicate数组赋值给了GradingSheet模型的字符串类型字段,导致类型不匹配。以下是正确的实现方案:

第一步:确认前端表单字段命名规范

动态表单的所有关联字段必须使用数组格式命名,确保同一条记录的字段共享相同的数组索引,示例如下:

<!-- 初始表单组 -->
<div class="form-row">
    <input type="hidden" name="point_id[]" value="1">
    <input type="text" name="competency_point[]" placeholder="能力项描述">
    <input type="number" name="grade[]" placeholder="评分">
    <textarea name="predicate[]" placeholder="评语"></textarea>
</div>

JS动态添加字段时,保持相同的命名格式(不要手动指定数组索引,让浏览器自动生成连续索引),确保提交后后端收到的数组中,相同索引的元素属于同一条记录。

##第二步:修正控制器Store方法逻辑
循环处理时,要根据point_id数组的索引,取出对应位置的其他字段值,而非直接存入整个数组:

public function store(Request $request)
{
    // 验证数组格式与字段合法性
    $validated = $request->validate([
        'point_id' => 'required|array',
        'competency_point' => 'required|array|same:point_id',
        'grade' => 'required|array|same:point_id',
        'predicate' => 'required|array|same:point_id',
        'point_id.*' => 'integer|exists:points,id',
        'competency_point.*' => 'string|max:255',
        'grade.*' => 'numeric|min:0|max:100',
        'predicate.*' => 'string',
    ]);

    // 循环插入每条记录
    foreach ($validated['point_id'] as $index => $pointId) {
        GradingSheet::create([
            'point_id' => $pointId,
            'competency_point' => $validated['competency_point'][$index],
            'grade' => $validated['grade'][$index],
            'predicate' => $validated['predicate'][$index],
            // 补充其他必填字段,如创建人ID等
        ]);
    }

    return redirect()->route('grading-sheets.index')->with('success', '评分记录保存成功');
}

注:same:point_id规则用于确保所有数组的长度一致,避免出现索引越界问题。

##第三步:检查模型批量赋值权限
确保GradingSheet模型已将需要存入的字段加入$fillable数组,允许批量赋值:

class GradingSheet extends Model
{
    use HasFactory;

    protected $fillable = [
        'point_id',
        'competency_point',
        'grade',
        'predicate',
        // 其他字段
    ];
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.02 05:12:19