laravel - 为同名但模型不同的表单字段添加验证规则
问题描述
在我的 Laravel 7 应用程序中,为了在表单中显示更好的错误消息,我使用了自定义验证属性。例如,对于在提交的表单字段中缺少时id
显示的字段。inventory number needed
现在的问题是我的应用程序中有几种不同模型的表单,并且有多个id
字段。还有一个id
是员工编号或流程编号。
但是在resources/lang/en/validation.php
我看不到为不同模型定义相同字段名称的方法。我的想法是重命名该字段以进行错误检查,例如id
重命名为employee_id
但没有出现错误消息。
在我看来:
<div class="form-group{{ $errors->has('id') ? ' ' : '' }}">
<input class="form-control{{ $errors->has('id') ? ' is-invalid' : '' }}" name="id" type="text" value="{{ old('id', $process->id) }}" aria-required="true"/>
@include('alerts.feedback', ['field' => 'employee_id']) //not working
</div>
从我的validation.php:
'attributes' => [
'email' => 'Mail Address',
'old_password' => 'Current Password',
'password' => 'Password',
'id' => 'Inventory Number', //working, for other form/model
'employee_id' => 'Employee ID' //not working
]
我认为问题在于只接受模型数据库中实际存在的字段名称。如何克服这一点?
解决方案
我刚刚找到了解决方案:定义自定义错误属性的更好方法validation.php
是为模型创建表单请求(https://laravel.com/docs/7.x/validation#creating-form-requests)并使用方法function attributes()
。所以与其他模型字段名称没有冲突而且更清楚,因为属性是在模型的表单请求中设置的:
<?php
namespace App\Http\Requests;
use App\Employee;
use Illuminate\Validation\Rule;
use Illuminate\Foundation\Http\FormRequest;
class EmployeeRequest extends FormRequest
{
(...)
public function attributes()
{
return [
'id' => 'Employee ID',
];
}
}
推荐阅读
- php - 使用前端控制器时在同一控制器上显示 Ajax 调用值
- html - 缩放 Svg 而不拉伸其中的一部分
- php - Laravel 无法在 eloquent 创建事件上设置 id
- windows - 扩展 Windows 安全模型
- tvos13 - 使用用 Xcode 11 编译的 tvOS 13 UITabBarController - tabBarObservedScrollView 滚动内容
- scala - 将两个列表与一个不同的元素组合在一起
- php - Laravel如何自动获取数组ID
- angular - Angular 如何使用 combineLatest 组合来自网站 url 栏的路由和查询
- npm - 如何在创建新的 Angular 8 项目时修复此 json 错误
- java - Drools 在 camelCase 中查找 Java 类,引发 NoClassDefFoundError