注册用户可以创建帖子,并且通过该帖子,用户可以上传多张图片。但是我遇到的问题是它无法正确验证文件上传。我用了:
mimes:jpg,jpeg,png
Run Code Online (Sandbox Code Playgroud)
但是,当我上传这些类型的图像时,它说它们不是。在实现多个图像上传之前,我上传了 1 个图像,这很好,但是当我上传多个图像时,它就破坏了。
这是我用于创建帖子的 postController.php 方法:
public function postCreatePost(Request $request){
//validates each field
$this->validate($request, [
'title' => 'required|max:100',
'type' => 'required',
'subtype' => 'required|max:100',
'date' => 'required|date',
'venue' => 'required|max:100',
'body' => 'required',
'cover_image' => 'required|mimes:jpeg,jpg,png'
]);
//adds each field sent in the request to the relevant post table column
$post = new Post();
$post->title = $request['title'];
$post->type = $request['type'];
$post->subtype = $request['subtype'];
$post->date = $request['date'];
$post->venue = $request['venue'];
$post->body = $request['body'];
$message = 'There was an error';
if($request->user()->posts($post)->save($post)){ //submits record to post table and if succesful it will enter loop
//creats image name and stores it in images table and stores the image in the cover_images directory
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]); // redirects user back to the dashboard
}
Run Code Online (Sandbox Code Playgroud)
尝试这个...
'cover_image.*' => 'required|mimes:jpeg,jpg,png'
Run Code Online (Sandbox Code Playgroud)
或这个 ...
'cover_image.*.file' => 'required|mimes:jpeg,jpg,png'
Run Code Online (Sandbox Code Playgroud)