gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-04 17:13:32 25 4
gpt4 key购买 nike

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

public function rules()
{
return [
//company
'companyName' => [
'required',
'string',
'min:3',
'max:100',
],
'country_id' => [
'nullable',
],
];
}
如何使 companyName 相对于 country_id 唯一?
谢谢

最佳答案

您可以为您的规则集创建自定义验证规则。
我建议你的 CountryhasMany()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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com