我有一個表格并獲取輸入值。輸入欄位之一是email。我需要檢查電子郵件在兩個不同的表中是否唯一,但需要在兩個表中允許值本身。嘗試了幾乎所有的組合,但無法解決。
$rules = [
'email' => "required|unique:admins|unique:vendors,email,$id",
];
上面的代碼有效,但警告說Email has already been taken. 但是當我只使用一張桌子時,它會按預期作業。也許有人可以幫助我,將不勝感激。
uj5u.com熱心網友回復:
這似乎是一個很好的用例Custom Validation Rules using Closures。基本上,不用使用一堆unique規則,您只需有一個function( closure),您可以在其中執行您的驗證邏輯來??決定是接受還是拒絕輸入。
$rules = [
/** added "email" rule to tell Laravel that we expect an email address */
'email' => ['required', 'email', function (string $attribute, string $value, Closure $fail) {
/** a function that checks whether an "email" exists in a "table" or not */
$existsInTableFN = fn(string $table): bool => DB::table($table)->where($attribute, $value)->exists();
/**
* the below condition means that the validation will FAIL
* if the "email" is found in one table but doesn't exist in the other
*/
if ($existsInTableFN('admins') !== $existsInTableFN('vendors'))
$fail('Email address already taken.'); /** laravel will take care of the rest if the above condition is met */
}]
];
概括:
上述closure規則僅在以下情況下接受電子郵件:
- 它在兩個表中都不存在
- OR 確實存在于它們兩者中
換句話說,closure規則將失敗:
- 如果它在一個表中找到提交的電子郵件
- 但它在另一個表中找不到它(提交的電子郵件)
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/506729.html
標籤:拉拉维尔
