laravel - Laravel 8 validate unique through columns and rows on create and update
问题描述
I have got 3 columns in my table email_1, email_2, email_3. How to avoid duplicates between the rows while create and update?
For the update method, I can validate by columns like this:
public function rules()
{
/** OTHER VALIDATION RULES */
'email_1' => [
'required',
'email',
'unique:users,email_1,' . $this->id,
],
'email_2' => [
'required',
'email',
'unique:users,email_2,' . $this->id,
],
'email_3' => [
'required',
'email',
'unique:users,email_3,' . $this->id,
]
/** OTHER VALIDATION RULES */
}
The problem is avoiding using the same email address on the three input fields of my form?
解决方案
方法一
最简单的方法是使用different
验证规则。像这样的东西:
'email_1' => [
'required',
'email',
'different:email_2'
'different:email_3',
'unique:users,email,' . $this->id,
],
'email_2' => [
'required',
'email',
'different:email_1'
'different:email_3',
'unique:users,email_2,' . $this->id,
],
'email_3' => [
'required',
'email',
'different:email_1'
'different:email_2',
'unique:users,email_3,' . $this->id,
],
方法二
我看到您正在Request
课堂上进行验证,这很棒,因为您可以使用After Hooks。
public function withValidator($validator)
{
$emails = [Request['email_1'], Request['email_2'], Request['email_3']];
$validator->after(function ($validator) use ($emails) {
if (count($emails) == count(array_unique($emails))) {
// Add error to message bag.
$validator->errors()->add('key', 'message');
}
});
}
上面的示例使用array_unique()
,它将删除重复项。比较原始长度与去重长度将显示是否存在重复。
推荐阅读
- python - PyQT5 fileDialoge 用于文件保存
- python - 如何从字典的值向现有字典添加顶层并使其嵌套?
- ios - 如何在拖动时删除单元格的阴影?
- html - 有多少种计算机语言有多个扩展名?
- oracle - 如何获取变量的值取决于 Oracle 12c 中的另一个变量?
- c++ - 如何为模板化运算符指定模板参数
- angular - 在 Angular 6 中使用 Laravel Passport
- android-studio - 未输入 URL 时,如何设置 editText 在 webView 中显示搜索结果
- react-native - setinterval 函数无限运行
- java - SQLite 方言进入 Hibernate-Maven 项目