Laravel:尝试上传多张图片时出错

时间:2018-04-23 17:18:55

标签: php html laravel

我试图允许注册用户创建帖子,在该帖子中,他们应该能够上传多个图片。然后应使用post_id将图像路径存储在images表中。指示图像的用途。 但是,当我单击提交按钮时,出现此错误:

 Illuminate \ Database \ QueryException (HY000)
SQLSTATE[HY000]: General error: 1364 Field 'cover_image' doesn't have a default value (SQL: insert into `posts` (`title`, `type`, `subtype`, `body`, `user_id`, `updated_at`, `created_at`) values (caged football, sport, Football, this is a description, 1, 2018-04-23 17:14:06, 2018-04-23 17:14:06))

这是我的PostController方法:

public function postCreatePost(Request $request){
    $this->validate($request, [
        'title' => 'required',
        'type' => 'required',
        'subtype' => 'required',
        'body' => 'required',
        'cover_image' => 'required'
    ]);

    $post = new Post(); 
    $post->title = $request['title'];
    $post->type = $request['type'];
    $post->subtype = $request['subtype'];
    $post->body = $request['body'];



    $message = 'There was an error';
    if($request->user()->posts($post)->save($post)){

        if($request->hasFile('cover_image')){
            foreach($request->file('cover_image') as $file){
                $filenameWithExt = $file->getClientOriginalName();
                $filename = pathinfo($filenameWithExt, PATHINFO_FILENAME);
                $extension = $file->getClientOriginalExtension();
                $fileNameToStore = $filename . '_' . time() . '.' . $extension; 
                $path = $file->storeAs('public/cover_images', $fileNameToStore);
                $image = new Image();
                $image->cover_image = $fileNameToStore;
                $image->post_id = $post->id;
                $image->save();
            }
        }

        $message = 'post successfully created';
    }

    return redirect()->route('dashboard')->with(['message' => $message]);
}

这是我的文件格式控件:

<div class="form-group">
    <label for="cover_image">Upload Image</label>
    <input type="file" name="cover_image[]" class="form-control" id="cover_image" multiple>
</div>

1 个答案:

答案 0 :(得分:1)

你在posts表中有一个名为cover_image的字段吗?我认为这是一个SQL错误