如何使 Laravel 唯一验证对输入数组起作用?

How to make Laravel unique validation work on an input array?

UpdateEntityRequest.php:

'phones'          => 'sometimes|nullable|array',
'phones.*.id'     => 'sometimes|required|integer|distinct|exists:entity_phones,id,entity_id,'.$this->id,
'phones.*.number' => 'required|alpha_num|max:255|distinct|unique:entity_phones,number,'.$this->id.',entity_id',

entity_phones table:

id, number, entity_id.
unique constraint: (number, entity_id)

EntityRepository.php:

foreach ($attributes['phones'] as $phone) {
    if (isset($phone['id'])) {
        $entity->phones()->updateOrCreate([
            'id'         => $phone['id'],
            'entity_id'  => $entity->id
        ], $phone);
    } else {
        $entity->phones()->create($phone);
    }
}

我的实体可以有超过 phone 个关联,但不能有重复的数字。我的目的是检查UpdateEntityRequest.php中的唯一(entity_id,数字)所以:

我在使用 Laravel 唯一规则时遇到问题,仅当我希望它进行验证时才进行验证。我将不胜感激任何关于如何制作此解决方案的想法。

如果您需要在唯一检查期间忽略给定的 ID,请尝试使用规则 class 来流畅地定义规则。

use Illuminate\Validation\Rule;

Validator::make($request_data, [
    'number' => [
        'required',
        'alpha_num', (...all your other rules)
        Rule::unique('entity_phones')->ignore($entity_id),
    ],
]);

您可以在 laravel 文档中阅读更多关于 unique rule 的段落:Forcing A Unique Rule To Ignore A Given ID。

我最终这样做了:

$phoneIds = $this->input('phones.*.id');

'phones.*.number' =>
                    [
                        'required_with:phones',
                        'alpha_num',
                        'max:255',
                        'distinct',
                        Rule::unique('entity_phones', 'number')
                        ->where('entity_id', $this->id)
                        ->where(function ($query) use ($phoneIds) {
                            return $query->where('id', '!=', array_shift($phoneIds));
                        })
                    ],