在 Laravel-8 中,我有这个独特的规则请求验证:
public function rules()
{
return [
//company
'companyName' => [
'required',
'string',
'min:3',
'max:100',
],
'country_id' => [
'nullable',
],
];
}
如何使 companyName 相对于 country_id 唯一?谢谢
最佳答案
您可以为您的规则集创建自定义验证规则。
我建议你的 Country
有 hasMany()
与 Company
的关系
public function rules()
{
return [
//company
'companyName' => [
'required',
'string',
'min:3',
'max:100',
function($attribute, $value, $fail) {
$country = Country::findOrFail(request()->get('country_id'));
if(!$country->companies()->whereName(request()->get('companyName'))->get()->isEmpty()) {
$fail('Woops, there\'s a country with this name. Type another one, please :)');
}
},
],
'country_id' => [
'nullable',
],
];
}
在此处阅读有关自定义 Laravel 验证规则的更多信息:https://laravel.com/docs/8.x/validation#custom-validation-rules
关于Laravel - 如何使用规则请求制作唯一的两个字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69055305/