【问题标题】:SQLSTATE[HY000]: General error: 1364 Field 'name' doesn't have a default valueSQLSTATE [HY000]:一般错误:1364 字段“名称”没有默认值
【发布时间】:2018-10-19 23:16:39
【问题描述】:

我正在使用 mysql v5.7laravel 5.5。当我尝试“添加产品”时,出现以下错误。

SQLSTATE[HY000]:一般错误:1364 字段“名称”没有 默认值

我的产品

 public function up()
    {
        Schema::create('products', function (Blueprint $table) {
            $table->increments('id');
            $table->string('name');
            $table->string('description');
            $table->string('size');
            $table->string('price');
            $table->string('image');
            $table->timestamps();
        });
    }

我的 ProductControllerstore 方法

public function store(Request $request)
{
    //validation
    $this->validate($request,[
        'name'=> 'required',
        'description'=>'required',
        'size'=>'required',
        'price'=>'required',
        'image'=>'image|mimes:png,jpg,jpeg|max:10000'
    ]);

    //image upload
    $image=$request->image;
    if($image){
        $imageName=$image->getClientOriginalName();
        $image->move('images',$imageName);
        $formInput['image']=$imageName;
    }

    Product::create($formInput);
    return redirect()->route('product.index');
}

当我在字段中添加->nullable方法时,没有错误但表中的数据为空。

请帮帮我...

【问题讨论】:

  • 有没有定义过$formInput?据我所知,它只有一个键,就是 image。

标签: mysql laravel


【解决方案1】:

您从未将经过验证的数据定义为变量。试试这个进行验证。

$formInput = $this->validate($request,[
    'name'=> 'required',
    'description'=>'required',
    'size'=>'required',
    'price'=>'required',
    'image'=>'image|mimes:png,jpg,jpeg|max:10000'
]);

这会将变量$formInput中的所有验证字段存储为一个数组。

【讨论】:

  • @BImoAnugrah 箭头下方应该有一个复选标记 - 单击它。
【解决方案2】:

请检查您是否在模型的 $fillables 中指定了名称字段。

受保护的 $fillables = ['name'];

【讨论】:

  • 您好,欢迎来到 Stack Overflow。我可以建议您编辑答案以通过将任何代码行括在 ` 字符之间或选择代码块并按 Ctrl+K 来提供代码格式
猜你喜欢
  • 2019-05-06
  • 2018-06-07
  • 2020-09-12
  • 2019-12-01
  • 2021-05-23
  • 2019-05-09
  • 2019-09-10
  • 2021-01-04
  • 2020-09-06
相关资源
最近更新 更多