doujiu3768 2018-05-25 23:54
浏览 52

Laravel多部分表单数据阵列验证

I've created a pretty basic form which contains two fields of array of file type.

<form id="form" method="post" action="{{ url("check") }}" enctype="multipart/form-data" files="true">
    {{ csrf_field() }}
    <input type="file" name="file[]">
    <input type="file" name="file[]">
    <input id="submit" type="submit">
</form>

I've added the enctype attribute for submission, however Laravel's validation system seems to not work properly. Indeed because errors are displayed for one field only :

{
  "name": [
    "file"
  ],
  "error": [
    "The file field is required."
  ]
}

I was expecting something like that (it displays when I remove the enctype attribute)

{
  "name": [
    "file.0",
    "file.1"
  ],
  "error": [
    "The file.0 must be a file of type: pdf, docx, odt.",
    "The file.1 must be a file of type: pdf, docx, odt."
  ]
}

For better understanding, here is my controller code :

public function validation(Request $request)
{
    $rules = [
        "file" => "required",
        "file.*" => "mimes:pdf,docx,odt"
    ];
    return Validator::make($request->all(),$rules);
}

public function check(Request $request)
{
    return response()->json(["name"=>$this->validation($request)->errors()->keys(),"error"=>$this->validation($request)->errors()->all()]);
}

I don't understand that issue, did I make a mistake or is that a bug from Laravel ? I'm using the 5.6 version by the way.

UPDATE

I've tried to implement my own rules, I've used a loop since fields are the same array :

$rules = [];

foreach($request->input('file') as $key => $value) {
    $rules["file.{$key}"] = 'required|mimes:pdf,docx,odt';
}
return Validator::make($request->all(),$rules);

But again it doesn't work WITH the enctype attribute.

Thank you a lot for your help.

  • 写回答

0条回答 默认 最新

    报告相同问题?

    悬赏问题

    • ¥100 set_link_state
    • ¥15 虚幻5 UE美术毛发渲染
    • ¥15 CVRP 图论 物流运输优化
    • ¥15 Tableau online 嵌入ppt失败
    • ¥100 支付宝网页转账系统不识别账号
    • ¥15 基于单片机的靶位控制系统
    • ¥15 真我手机蓝牙传输进度消息被关闭了,怎么打开?(关键词-消息通知)
    • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
    • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
    • ¥15 手机接入宽带网线,如何释放宽带全部速度