我在同时验证多个文件和文字时遇到了一些麻烦。
当我验证整个请求$request->all();
时,文件规则不起作用。
'file' => 'required|mimes:png,jpeg,jpg,gif|max:3000'
。
如果我只验证数组array('file'=> $file)
中的文件,那会得到修复,但这样我就无法验证其他输入。
我从互联网上获得了多个文件部分,并为其他输入添加了我的部分,这是我的功能:
public function createNewPost(Request $request) {
$post = new Post;
$post->user_id = Auth::user()->id;
$post->title = $request->input('title');
$post->body = $request->input('body');
$post->status= "borrador";
$post->save();
$post->img = "/uploads/posts/".$post->id;
$post->save();
$files = Input::file('file');
$file_count = count($files);
$uploadcount = 0;
foreach($files as $file) {
$rules = array(
'file' => 'required|mimes:png,jpeg,jpg,gif|max:3000',
'title' => 'required|unique:posts|max:255',
'body' => 'required'
);
$messages = [
'title.required' => 'Sin titulo?',
'body.required' => 'No has escrito nada',
'file.required' => 'Selecciona al menos 1 imagen.',
'file.mimes' => 'No puedes utilizar ese tipo de imagen, intenta con (jpg/png/jpeg).',
'file.max' => 'El total de imagenes no puede pesar mas de 3MB.'
];
$validator = Validator::make(array('file'=> $file), $rules, $messages);
if($validator->passes()){
$destinationPath = 'uploads/posts/'.$post->id;
//$filename = $file->getClientOriginalName();
$filename = $uploadcount.".".$file->getClientOriginalExtension();
$upload_success = $file->move($destinationPath, $filename);
$uploadcount ++;
}
}
if($uploadcount == $file_count){
Session::flash('success', 'Upload successfully');
return Redirect::to('/admin/post/new');
}
else {
return Redirect::to('/admin/post/new')->withInput()->withErrors($validator);
}
}
答案 0 :(得分:2)
试试这个,并删除你的foreach文件循环:
$files = count($this->input('file')) - 1;
foreach(range(0, $files) as $index) {
$rules['file.' . $index] = 'required|mimes:png,jpeg,jpg,gif|max:3000';
}