Laravel基于2个值的验证规则

huangapple go评论72阅读模式
英文:

Laravel validation rules based on 2 values

问题

我有一个表单,它将两个值property_idemail发布到一个端点。

目前,我有以下形式验证;

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'],
    ];
}

huangapple
  • 本文由 发表于 2023年7月6日 19:22:43
  • 转载请务必保留本文链接:https://go.coder-hub.com/76628303.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定