Laravel - 如何使用规则请求使两个字段唯一
Laravel - How to make unique two fields using rules request
在 Laravel-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
在 Laravel-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