Laravel 5.5添加产品触发MySQL 1364字段无默认值错误求助
解决SQLSTATE[HY000]: General error: 1364 Field 'name' doesn't have a default value 问题
Let's break down what's going on here and fix this step by step:
问题根源分析
这个错误和后续的空值问题,本质上是两个核心问题导致的:
- MySQL严格模式限制:MySQL 5.7默认开启严格模式,当你尝试给非
nullable的字段插入空值时,就会抛出1364错误。你添加->nullable()只是绕过了错误,但并没有解决"没有把表单数据写入数据库"的根本问题,所以字段才会是空的。 - 表单数据收集与批量赋值遗漏:你的
store方法只处理了image字段,完全没把name、description这些必填字段加入到插入数组中;另外,Laravel的create()方法需要模型允许批量赋值,否则即使传递了字段也不会生效。
步骤1:修复表单数据收集逻辑
修改你的store方法,把所有验证通过的字段都纳入插入数组:
public function store(Request $request) { // 验证逻辑保持不变 $this->validate($request,[ 'name'=> 'required', 'description'=>'required', 'size'=>'required', 'price'=>'required', 'image'=>'image|mimes:png,jpg,jpeg|max:10000' ]); // 先收集所有验证通过的字段(排除image,单独处理) $formInput = $request->except('image'); // 处理图片上传(仅当存在图片时执行) if($request->hasFile('image')){ $image = $request->image; $imageName = $image->getClientOriginalName(); $image->move('images', $imageName); $formInput['image'] = $imageName; } // 创建产品记录 Product::create($formInput); return redirect()->route('product.index'); }
步骤2:配置Product模型允许批量赋值
打开app/Product.php模型文件,添加$fillable属性,列出所有可以批量赋值的字段:
namespace App; use Illuminate\Database\Eloquent\Model; class Product extends Model { // 允许批量赋值的字段列表 protected $fillable = ['name', 'description', 'size', 'price', 'image']; }
为什么加nullable()后数据为空?
当你给字段添加->nullable()后,MySQL允许这些字段存储空值,但你的代码依然没有把表单提交的name、description等字段值传递给插入逻辑,所以数据库自然会存入空值——这只是掩盖了错误,并没有真正解决数据写入的问题。
额外优化提示
如果后续需要允许用户不上传图片,可以做两个调整:
- 迁移文件中把
image字段设为可空:$table->string('image')->nullable(); - 验证规则中给
image添加nullable:'image'=>'nullable|image|mimes:png,jpg,jpeg|max:10000'
内容的提问来源于stack exchange,提问作者bimoan
相关产品推荐
相关产品推荐

