Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Validating composite key in an array of data in request class

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

"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.

>Solution :

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'])
    ),
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading