Home > Software design >  Validating composite key in an array of data in request class
Validating composite key in an array of data in request class

Time:10-05

Have been trying every possible solution to validate that the combination of country_id and phone number is unique for every new user inside an array.

This is my latest attempt

   foreach(request()->get('contacts') as $contactKey => $contactVal) {
        $rules["contacts.$contactKey.phone"] = [
            'required',
            'string',
            Rule::unique('users')
                ->where(
                    fn($query) => $query
                        ->where('phone', $contactVal['phone'])
                        ->where('country_id', $contactVal['country_id'])
                ),
            ];
    }

I see no reason why this should not work but am currently getting the error:

"SQLSTATE[42S22]: Column not found: 1054 Unknown column 'contacts.0.phone' in 'where clause' (SQL: select count(*) as aggregate from `users` where `contacts`.`0`.`phone` = 61477261 and (`phone` = 61477261 and `country_id` = 208))"

Writing a rule like this inside a foreach seems to work fine but it throws an error as soon as I put the Rule::unique inside.

CodePudding user response:

You have to pass column name as second argument Rule::unique(table, column)

Rule::unique('users', 'phone')
    ->where(
        fn($query) => $query
            ->where('phone', $contactVal['phone'])
            ->where('country_id', $contactVal['country_id'])
    ),
  • Related