在larvel -8中我有这个独特的规则请求验证:
public function rules()
{
return [
//company
'companyName' => [
'required',
'string',
'min:3',
'max:100',
],
'country_id' => [
'nullable',
],
];
}
如何使companyName相对于country_id唯一?
感谢您可以为您的规则集创建一个自定义的验证规则。
我建议您的Country
与Company
具有hasMany()
关系
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