0

当表单文件名总是不同时,我将如何为请求中的每个图像运行验证器。

我的表单文件名可以从file1一直到section_1_image[0][].

我需要创建一个可以粘贴到每个控制器中的验证,它检查发布请求并验证所有文件(如果有的话)

这是我到目前为止所拥有的

    $validator = Validator::make($request->all(), [
        'items' => 'array',
    ]);

    $validator->each('items', [
        '*'       => 'max:50'
    ]);

    if ($validator->fails()) {
        echo 'Error';
        exit;
    }

但这似乎没有任何作用,它只是被忽略了吗?

4

2 回答 2

0

使用请求中存在的文件名构建自定义规则数组,并根据它验证请求。

use Illuminate\Support\Facades\Input;

//code

$rule = [];

foreach (Input::file() as $key => $value) {
    $rule = $rule + [$key => 'max:50'];
}

$validator = Validator::make($request->all(), $rule);

if ($validator->fails()) {
    //validation failed
    //custom error message common for all file(optional)
    $validator->errors()->add('image_size_error', 'Images size exceeds!');

    return redirect()
                ->back()
                ->withErrors($validator)
                ->withInput();
}

希望能帮助到你..

于 2018-05-17T18:38:06.877 回答
0

我建议您将所有文件名更改为类似files[ file_name]

<input type="file" name="files[first]">
<input type="file" name="files[section_1_image]">

这样在您拥有的每个控制器中

$validator = Validator::make($request->all(), [
    ...
    'files.*' => 'file_rules...',
]);
于 2018-05-17T12:15:10.333 回答