我无法在laravel 5.4中通过变量名称验证多个表格

时间:2017-05-15 09:50:37

标签: validation laravel-5.4

我正在使用Laravel 5.4 我的创建形式是多语言的多领域。我的表单中的字段名称是可变的:

    public function store(Request $request)
{
           $validator = Validator::make($request->all(), [
               'subject' => 'required|max:255',
               'content' => 'required|max:255',                
           ]);
    $languages = Languages::all();
    $page = new Page();
    $page->save(); // Eloquent

    foreach ($languages as $language) {
        $pageTrans = new PageTrans();
        $pageTrans['page_id']= $page->id;
        $pageTrans['locale'] = $language->locale;
        $pageTrans['subject'] = $request->input('subject_' . $language->code);
        $pageTrans['content'] = $request->input('content_' . $language->code);
        $pageTrans->save(); // Eloquent
    }

    return redirect(route('pages.index'));
}

和我的控制代码:

maps.googleapis.com

但有问题但没有检测到feild名称。你知道一个解决方案或更好的方法吗?

1 个答案:

答案 0 :(得分:0)

你可以改变你的控制器。我没有测试过。如果有任何问题,请告诉我。

    $languages = Languages::all();
    if( $languages->count() ){
        $data = [];
        foreach ($languages as $language) {
            $data['subject_'.$language->code] = 'required|max:255';
            $data['content_'.$language->code] = 'required';
        }
        $validator = Validator::make($request->all(), $data);
        if ($validator->fails()) {
            return redirect(route('pages.store'))
                        ->withErrors($validator)
                        ->withInput();
        }else{
            $page = new Page();
            $page->save(); // Eloquent

            foreach ($languages as $language) {
                $pageTrans = new PageTrans();
                $pageTrans['page_id']= $page->id;
                $pageTrans['locale'] = $language->locale;
                $pageTrans['subject'] = $request->input('subject_' . $language->code);
                $pageTrans['content'] = $request->input('content_' . $language->code);
                $pageTrans->save(); // Eloquent
            }
            return redirect(route('pages.index'));
        }
    }

谢谢!