我目前正忙于解决这个问题。我是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
有人能帮我或给我指个正确的方向吗?谢谢!
- 添加
name="city[{{$i}}]"
- 使用php artisan make创建特定请求:request PostRequest
- 将
public function Postdata(Request $request) {
更改为public function Postdata(PostRequest $request) {
- 从控制器中删除验证函数调用
- 转到/app/Http/Requests/PostRequest.php
- 然后将规则函数编辑为这样
/**
* Get the validation rules that apply to the request.
*
* @return array
*/
public function rules()
{
$rules = [];
foreach($this->request->get() as $key => $val)
{
$rules['address.' . $key] = 'required';
$rules['city.' . $key] = 'required';
}
return $rules;
}
谢谢你,伙计!这就是我最终使用的解决方案
<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;
}