Laravel -如何使用规则请求来使两个字段唯一



在larvel -8中我有这个独特的规则请求验证:

public function rules()
{
return [
//company
'companyName' => [
'required',
'string',
'min:3',
'max:100',
],
'country_id' => [
'nullable',
],
];
}

如何使companyName相对于country_id唯一?

感谢

您可以为您的规则集创建一个自定义的验证规则。

我建议您的CountryCompany具有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

最新更新