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

Laravel validation for option list: if value is not in DB then give error

I have an option list in my front end and the data is retrieved from the DB table, named countries and nicename column.

enter image description here

Trying to prevent the user request for value which is not in countries table and in nicename column. I have created custom validation, which works fine but it looks like it’s not too professional way of doing this control. I have seen somewhere that there is shorter way of doing this validation by in:table_name,column_name. But it did not work for me Maybe I am doing something wrong?

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

$rules = [
 'shop_country' => [
                            'required',
                            function ($attribute, $value, $fail ) {
                            $found_country = '';
                                $countries = Country::get()->toArray();
                                foreach ($countries as $country) {
                                  if ($country['nicename'] === $value) {
                                      $found_country= $country['nicename'];
                                  }
                                }
                                if($found_country === ''){
                                    $fail('The country is not valid!');
                                }
                            }],
] 

Any help would be highly appreciated.

>Solution :

You can define it as:

'shop_country' => ['required|exists:table_name,column']

See docs

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