英文:
Laravel validation rules based on 2 values
问题
我有一个表单,它将两个值property_id
和email
发布到一个端点。
目前,我有以下形式验证;
return [
'email' => ['required', 'email'],
'property_id' => ['required', 'exists:properties,id'],
];
这样做得很好,但我还想检查invites
表,看看该电子邮件是否已经存在于该property_id
下。如果存在,我想在电子邮件中返回一条消息,内容是'An invitation for this email and property already exists'。
这是可能的吗?
英文:
I have a form which posts 2 values property_id
and email
to an endpoint.
Currently I have form validation which is as follows;
return [
'email' => ['required', 'email'],
'property_id' => ['required', 'exists:properties,id'],
];
This does alright, but what i want to also do is check the invites
table to see if the email already exists against that property_id. If it does i want to return a message in the email that says 'An invitation for this email and property already exists'
Is that possible?
答案1
得分: 2
是的,您可以使用 闭包 来完成这个任务。
public function rules()
{
return [
'email' => [
'required',
'email',
function ($attribute, $value, $fail) {
$propertyId = $this->input('property_id');
$invitationExists = DB::table('invites')
->where('email', $value)
->where('property_id', $propertyId)
->exists();
if ($invitationExists) {
$fail('此电子邮件和属性已存在邀请。');
}
},
],
'property_id' => ['required', 'exists:properties,id'],
];
}
英文:
yes, you can do it using closure
public function rules()
{
return [
'email' => [
'required',
'email',
function ($attribute, $value, $fail) {
$propertyId = $this->input('property_id');
$invitationExists = DB::table('invites')
->where('email', $value)
->where('property_id', $propertyId)
->exists();
if ($invitationExists) {
$fail('An invitation for this email and property already exists.');
}
},
],
'property_id' => ['required', 'exists:properties,id'],
];
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论