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

Laravel提交数据报错:Field 'description'无默认值问题排查

Laravel插入数据报错SQLSTATE[HY000]: 1364的问题分析与解决

报错核心原因

数据库表tb_desc中的description字段被设置为非空且无默认值,但执行插入操作时,没有向该字段传入任何值,导致数据库抛出约束错误。从报错的SQL语句也能看出:insert into tb_desc (month_year, updated_at, created_at)里完全没包含description字段。

可能的代码问题及解决方法

1. Model未允许description字段批量赋值

打开Description.php,检查$fillable属性是否包含description。Laravel的批量赋值(比如create()方法)只会写入$fillable里声明的字段,如果漏了description,即使请求里传了值也不会被插入。

修正后的Model示例:

<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;

class Description extends Model
{
    protected $table = 'tb_desc';

    // 确保$fillable包含description
    protected $fillable = ['month_year', 'description'];
}

2. Controller未获取或传入description字段

检查DescriptionController.php的store方法,确认是否正确获取了请求中的description值,并且将其加入到插入数据中。

错误示例(遗漏description):

public function store(Request $request)
{
    Description::create([
        'month_year' => $request->input('month_year'),
        // 漏了description字段
    ]);
}

修正后的示例:

public function store(Request $request)
{
    // 先验证必填字段,避免空值提交
    $request->validate([
        'month_year' => 'required',
        'description' => 'required', // 强制验证该字段存在且非空
    ]);

    // 使用验证后的完整数据插入
    Description::create($request->validated());
}

3. 前端表单未提交description值

如果前端表单里没有description对应的输入框,或者输入框的name属性写错了,也会导致后端接收不到该字段值。需要确认前端表单的description输入框name属性正确,且表单提交时该字段有值。

可选方案(如果业务允许为空)

如果业务逻辑中description字段可以为空,可以修改数据库表结构,将该字段设置为允许为空(nullable)。可以通过Laravel迁移实现:

Schema::table('tb_desc', function (Blueprint $table) {
    $table->text('description')->nullable()->change();
});

执行迁移命令:php artisan migrate


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.31 23:45:23