簡體   English   中英

驗證數組中的復合鍵?

[英]Validate composite key within array?

為了在我的應用程序中驗證電話號碼,我需要將它與國家 ID 結合起來,以確保組合是唯一的,而不是電話號碼本身。 這在過去不是問題,已經在驗證類中使用以下方法解決了

   'phone' => ['required', 'string',
            Rule::unique('users')
                ->where('country_id', $this->country_id)
                ->where('phone', $this->phone)
        ],

但是我現在接受了一系列用戶並且以下規則似乎不起作用

  'contacts.*.phone' => ['required', 'string',
            Rule::unique('users')
                ->where('country_id', $this->country_id)
                ->where('phone', $this->phone)
        ],

尚未在堆棧溢出或文檔中找到任何有關此問題的信息

您可以使用Rule::forEach實現此目的,在您的用例中它可能如下所示:

'contacts.*.phone' => [
    'required',
    'string',
    Rule::forEach(function ($value, $attribute) {
        return [
            Rule::unique('users')
                ->where('country_id', $value)
                ->where('phone', $value),
        ];
    }),
],

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM