Laravel 表单验证唯一使用 2 个字段

Laravel form validation unique using 2 fields(Laravel 表单验证唯一使用 2 个字段)
本文介绍了Laravel 表单验证唯一使用 2 个字段的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着跟版网的小编来一起学习吧!

问题描述

如何在 2 个字段上设置唯一的验证规则?

How can I have a unique validation rule on 2 fields?

一个.应用程序不应允许两个人具有相同的名字和姓氏.

a. The application should not allow two people to have the same identical first name and last name.

允许用户只填写名字或只填写姓氏.因为用户可能只有其中之一.

It is allowed that the users fills in only a first name or only a last name. Because the user may have only one of them.

B.但是,如果用户只输入名字 (Glen),则表中的其他人不应具有相同的名称(名字 = 'Glen' 且姓氏 = null).另一个格伦史密斯"还可以.

b. But if the user enters only a first name (Glen), no other person in the table should have the same (first name = 'Glen' and last name = null). another 'Glen Smith' ok.

我尝试了以下规则.当两个字段(名字和姓氏)都不为空时,它工作得很好:

I tried the following rule. It works great when both fields (first and last name) are not null:

'firstName' => 'unique:people,firstName,NULL,id,lastName,' . $request->lastName

此规则在 b 上失败.当只有一个字段时.

This rule fails on b. when only one field is present.

有什么提示吗?

推荐答案

内置的 unique 验证器不会真正支持您尝试执行的操作.它的目的是确保单个有效值在数据库中是唯一的,而不是两个值的组合.但是,您可以创建一个自定义验证器:

The built in unique validator wouldn't really support what you're trying to do. It's purpose is to ensure that a single valid is unique in the database, rather than a composite of two values. However, you can create a custom validator:

Validator::extend('uniqueFirstAndLastName', function ($attribute, $value, $parameters, $validator) {
    $count = DB::table('people')->where('firstName', $value)
                                ->where('lastName', $parameters[0])
                                ->count();

    return $count === 0;
});

然后您可以通过以下方式访问此新规则:

You could then access this new rule with:

'firstName' => "uniqueFirstAndLastName:{$request->lastName}"

您可能会发现您可能需要稍微调整您的数据库查询,因为它未经测试.

You'll probably find you might need to tweak your database query a little bit as it's untested.

这篇关于Laravel 表单验证唯一使用 2 个字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

本站部分内容来源互联网,如果有图片或者内容侵犯了您的权益,请联系我们,我们会在确认后第一时间进行删除!

相关文档推荐

DeepL的翻译效果还是很强大的,如果我们要用php实现DeepL翻译调用,该怎么办呢?以下是代码示例,希望能够帮到需要的朋友。 在这里需要注意,这个DeepL的账户和api申请比较难,不支持中国大陆申请,需要拥有香港或者海外信用卡才行,没账号的话,目前某宝可以
PHP通过phpspreadsheet导入Excel日期,导入系统后,全部变为了4开头的几位数字,这是为什么呢?原因很简单,将Excel的时间设置问文本,我们就能看到该日期本来的数值,上图对应的数值为: 要怎么解决呢?进行数据转换就行,这里可以封装方法,或者用第三方的
mediatemple - can#39;t send email using codeigniter(mediatemple - 无法使用 codeigniter 发送电子邮件)
Laravel Gmail Configuration Error(Laravel Gmail 配置错误)
Problem with using PHPMailer for SMTP(将 PHPMailer 用于 SMTP 的问题)
Issue on how to setup SMTP using PHPMailer in GoDaddy server(关于如何在 GoDaddy 服务器中使用 PHPMailer 设置 SMTP 的问题)