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

Laravel调用update方法更新学生表仅first_name字段生效问题

问题原因

  • Laravel Eloquent的update()方法仅接受一个包含所有待更新字段键值对的关联数组作为入参,你当前代码将每个字段拆分为独立数组传入,方法仅会识别第一个数组中的first_name字段,剩余参数会被直接忽略。
  • 代码中birthday字段的键值分隔符错误写为逗号,,应改为箭头=>。

修复方案

将所有待更新字段合并到同一个关联数组中传入update()方法即可,修正后的代码如下:

public function editStudent(Request $request)
{
    $studId = $request->get('studId');
    $studFirstName = $request->get('firstName');
    $studLastName = $request->get('lastName');
    $studGender = $request->get('gender');
    $studBirthday = $request->get('birthday'); 
    $studSchoolId = $request->get('schoolId'); 
    $update = Student::where('id', $studId)->update([
        'first_name' => $studFirstName,
        'last_name' => $studLastName,
        'gender' => $studGender,
        'birthday' => $studBirthday,
        'school_id' => $studSchoolId
    ]); 
    return response()->json([
        "update" => $update,
    ]);
}

额外注意事项

如果修改后仍有字段无法更新,请检查Student模型中$fillable属性是否配置了所有允许批量赋值的字段,示例配置参考:

// app/Models/Student.php
protected $fillable = [
    'first_name',
    'last_name',
    'gender',
    'birthday',
    'school_id'
];

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.01 15:39:02