我正在使用 Laravel 构建一个包含输入数组的表单,并且在发生验证错误时我很难显示翻译后的属性名称。为简单起见,我将发布一个简单的问题示例。
视图内的表单:
<form method="POST" action="{{ route('photo.store') }}" accept-charset="UTF-8" role="form">
<input name="_token" type="hidden" value="{{ csrf_token() }}">
<div class="row">
<div class="col-lg-12">
<div class="form-group{{ $errors->has('testfield') ? ' has-error' : '' }}">
<label class="control-label"
for="testfield">{{ trans('validation.attributes.testfield') }}</label>
<input class="form-control" name="testfield" type="text" id="testfield"
value="{{ old('testfield') }}">
@if ($errors->has('testfield'))
<p class="help-block">{{ $errors->first('testfield') }}</p>
@endif
</div>
</div>
<div class="col-lg-12">
<div class="form-group{{ $errors->has('testfieldarray.0') ? ' has-error' : '' }}">
<label class="control-label"
for="testfieldarray-0">{{ trans('validation.attributes.testfieldarray') }}</label>
<input class="form-control" name="testfieldarray[]" type="text" id="testfieldarray-0"
value="{{ old('testfieldarray.0') }}">
@if ($errors->has('testfieldarray.0'))
<p class="help-block">{{ $errors->first('testfieldarray.0') }}</p>
@endif
</div>
</div>
<div class="col-lg-12">
<div class="form-group{{ $errors->has('testfieldarray.1') ? ' has-error' : '' }}">
<label class="control-label"
for="testfieldarray-1">{{ trans('validation.attributes.testfieldarray') }}</label>
<input class="form-control" name="testfieldarray[]" type="text" id="testfieldarray-1"
value="{{ old('testfieldarray.1') }}">
@if ($errors->has('testfieldarray.1'))
<p class="help-block">{{ $errors->first('testfieldarray.1') }}</p>
@endif
</div>
</div>
</div>
<div class="row">
<div class="col-lg-12">
<input class="btn btn-primary" type="submit" value="Gravar">
</div>
</div>
表单请求中的规则功能:
public function rules() {
$rules = [
'testfield' => array('required'),
];
foreach ($this->request->get('testfieldarray') as $key => $val) {
$rules['testfieldarray.' . $key] = array('required');
}
return $rules;
}
lang/en/validation.php
'attributes' => [
'testfield' => 'Test Field',
'testfieldarray' => 'Test Field Array',
],
验证正确执行,错误消息也是如此。错误消息中的唯一问题是显示的属性名称。在两个数组输入中,插入到消息中的属性名称是“testfieldarray.0”和“testfieldarray.1”,而不是“Test Field Array”。我已经尝试添加语言文件 'testfieldarray.0' => 'Test Field Array', 'testfieldarray.1' => 'Test Field Array',但消息保持不变。有没有办法正确传递属性名称?