Home>

I want to determine if it is unique in the request passed in the array
If the same value is entered in test_col of table_hogehoge, I want to get an error saying that the same value cannot be entered.
I want to apply validation
What should I do for unique validation in the request item?

Corresponding source code ・ What I tried

I wrote that test_col is unique in table_hogehoge.

I wrote the following validation

  return [
        '*' =>['required','array'],
        '* .id' =>['required','string'],
        '* .test_col' =>['required','string', Rule :: unique ('table_hogehoge','test_col')->ignore ($this->route ('id'))
    ];;

If i actually enter 4 records and move it,

The value of 0.test_col already exists.
1. The value of test_col already exists.
2. The value of test_col already exists.
3. The value of test_col already exists.

Will come out.
I think it's because there is a value I'm trying to update
It is unique in the request array.
What should I do for unique validation in the request item?

  • Answer # 1

    If it seems difficult to realize with existing rules, why not create a custom rule?
    Also, as you can see in the documentation,
    Link content

    Note: Never pass user-controlled request input to the ignore method. Instead, pass only the unique generated ID, such as the auto-incremental ID or UUID of the Eloquent model instance. Otherwise, your application will be vulnerable to SQL injection attacks.

    There is. be careful.

  • Answer # 2

    I created a custom validator as follows
    I rotated the array data and added a unique rule only for those that met the conditions.

      public function rules (): array
        {
            $rules = [
            '*' =>['required','array'],
            '* .id' =>['required','string'],
            ];;
            foreach ($this->all () as $k =>$v) {
      If (conditional expression) {
                    $rules = array_merge ($rules, [
                        "${k} .test_col" =>['required','string', Rule :: unique ('test_hoghoge','key')->ignore ($v ['id'] ?? null)]
                    ]);
            }
            return $rules;
        }