dtkvlj5386 2018-04-23 17:18
浏览 84
已采纳

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

I'm trying to allow a registered user to create a post and in that post, they should be able to upload multiple images. The image path should then be stored in the images table with the post_id. Indicating which post the image is for. However, when I click the submit button I am presented with this error:

 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))

Here is my PostController method:

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]);
}

Here is my file form control:

<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条回答 默认 最新

  • doujiu9307 2018-04-23 17:25
    关注

    do you have a field named cover_image in the posts table? I think it's a SQL error

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥50 三种调度算法报错 采用的你的方案
  • ¥15 关于#python#的问题,请各位专家解答!
  • ¥15 对于这个问题的解释说明
  • ¥200 询问:python实现大地主题正反算的程序设计,有偿
  • ¥15 smptlib使用465端口发送邮件失败
  • ¥200 总是报错,能帮助用python实现程序实现高斯正反算吗?有偿
  • ¥15 对于squad数据集的基于bert模型的微调
  • ¥15 为什么我运行这个网络会出现以下报错?CRNN神经网络
  • ¥20 steam下载游戏占用内存
  • ¥15 CST保存项目时失败