【问题标题】:SQL default value error when uploading files using laravel使用laravel上传文件时SQL默认值错误
【发布时间】:2019-10-10 09:37:06
【问题描述】:

我正在尝试使用 laravel 上传多张图片,到目前为止我已经成功,但问题是当我尝试保存文本 AND 文件时出现错误。 到目前为止,我收到了很多错误,以至于我都不记得了,但最新的是:

SQLSTATE[HY000]:一般错误:1364 字段“标题”没有默认值(SQL:插入到posts(image,updated_at,created_at)值([“italian. jpg"], 2019-05-23 18:48:22, 2019-05-23 18:48:22))

我已经正确设置了 sql,正如我所说,如果我删除图像上传它可以工作,如果我删除文本字段它也可以工作,但是 如果我都尝试我不会 . 如果我没记错的话,当我删除必填字段时它也可以工作。

公共函数存储(请求 $request) { //dd($request);

    $this->validate($request, [
        'title' => 'required|min:3|max:120',
        'text' => 'required',
        'image' => 'required',
        'image.*' => 'image|mimes:jpeg,png,jpg,gif,svg|max:2048'
    ]);

    if($request->hasfile('image')){
        foreach($request->file('image') as $image)
        {
            $name=$image->getClientOriginalName();
            $image->move(public_path().'/images/', $name);  
            $data[] = $name;  
        }
    } else{
        redirect('/posts')->with('Error', 'no image');
    }

    $post->image=json_encode($data);

    $post = Post::create($validatedData);

    return redirect('/posts')->with('success', 'yay');

}

我也试过了,但它返回了

从空值创建默认对象

public function store(Request $request)
{
     $validatedData = $request->validate([
        'title' => 'required|min:3|max:120',
        'category' => 'required|min:3|max:120',
        'text' => 'required',
        'image' => 'required',
        'image.*' => 'image|mimes:jpeg,png,jpg,gif,svg|max:2048',
    ]);


    if($request->hasfile('image'))
     {

        foreach($request->file('image') as $image)
        {
            $name=$image->getClientOriginalName();
            $image->move(public_path().'/images/', $name);  
            $data[] = $name;  
        }
     }

     $post = new Post();
     $post->image=json_encode($data);


    $post->save();

    return back()->with('success', 'Yay');



}

【问题讨论】:

  • 你的班级有 2 个store 方法吗??
  • 确保您的模型中有 fillable title 属性
  • 看起来您没有将值传递给字段标题/文本/类别,但这些字段是必需的。请确保您的视图(刀片)中有这些字段并且具有价值。
  • 抱歉给我带来了麻烦,我发布问题时很着急。只有一种存储方法,最后一种只是我尝试过的方法,但也失败了。是的,这些字段都是可填写的,我正在发送视图中的值。正如我所说,如果我尝试 only 它可以工作的文本字段,如果我尝试 only 它也可以工作的图像。问题是当我尝试两者时。

标签: php laravel controller


【解决方案1】:

我想通了,呵呵。只需要删除这些行:

'image' => 'required', 'image.*' => 'image|mimes:jpeg,png,jpg,gif,svg|max:2048'

还是谢谢。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-03-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-01-11
    • 2017-07-29
    • 1970-01-01
    • 2018-04-24
    相关资源
    最近更新 更多