表格数组验证Laravel 5.2

时间:2016-05-03 18:43:04

标签: php html arrays laravel-5 laravel-5.2

我目前仍坚持解决这个问题。我是Laravel和MVC框架的新手。我正在努力创建动态表单,使用户能够添加尽可能多的表单。当用户首先进入页面时,它会生成5个表单域。以下是我目前的代码。

<div id ={{$id = "from".$i}} >


  <div  class="form-group col-md-6">


                  <div  class="col-md-6   form-group">

                        <label for={{$id = "Address".$i}}>Address</label>
                        <input type="text" name = "address[{{$i}}]" class="form-control" id={{$id = "Address".$i}} placeholder="Street Address"> <!-- problem form array how does this work in laravel --> 


                </div>


                  <div  class="form-group col-md-6">

                         <label for={{$id = "city".$i}}>City</label>
                         <input type="text" value = "{{ old('city') }}" class="form-control" id={{$id = "City".$i}} placeholder="City">

                            @if ($errors->has('city'))
                                <span class="help-block">
                                    <strong>{{ $errors->first('city') }}</strong>
                                </span>
                            @endif
              </div>

如何使用数组

验证Laravel 5.2中的表单

这是我的控制器

  public function Postdata(Request $request) { 

             $this->validate($request->all(), [
                'address.*' => 'required|string',
               'city' => 'required',
                  ]);

               }

我使用for循环动态生成表单。

这是我得到的错误

      ErrorException in ValidatesRequests.php line 49:
      Argument 1 passed to App\Http\Controllers\Controller::validate() must be                    an instance of Illuminate\Http\Request, array given, called in           
  C:\wamp\www\Dynamic- 1.0\app\Http\Controllers\propContoller.php on line 34 and defined

有人可以帮助或指出我正确的方向,谢谢你!

2 个答案:

答案 0 :(得分:1)

  1. 添加dotnet publish
  2. 使用php artisan make:request PostRequest
  3. 创建一个特定请求
  4. name="city[{{$i}}]"更改为public function Postdata(Request $request) {
  5. 从控制器中删除验证功能调用
  6. 转到/app/Http/Requests/PostRequest.php
  7. 然后将规则功能编辑为类似的内容......
  8. public function Postdata(PostRequest $request) {

答案 1 :(得分:0)

谢谢你!这是我最终的解决方案

  <div  class="form-group col-md-6">


                  <div  class="col-md-6   form-group">

                        <label for={{$id = "Address".$i}}>Address</label>
                        <input type="text"  name="address[{{$i}}]" class="form-control" id={{$id = "Address".$i}} placeholder="Street Address">


                </div>

在帖子请求中我做了这个

public function authorize()
{
    return true;
}

      /**
        * Get the validation rules that apply to the request.
        *
        * @return array
       */

    public function rules() {

    $rules = [];

       foreach($this->request->get('address') as $key => $val) {

       $rules['address.'.$key] = 'required';

       }

       return $rules;
      }