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

Time:09-16

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?

$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!');
                                }
                            }],
] 

CodePudding user response:

You can define it as:

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

See docs

CodePudding user response:

You may use the exists validation rule:

The field under validation must exist in a given database table.

$rules = [
  'shop_country' => ['required', 'exists:countries,nicename']
];

In the above example, the table name is assumed to be countries.

CodePudding user response:

You should be able to achieve this by using the exists validation rule. You can check it in the official laravel documentation.

Also this is an example they provide

'state' => 'exists:states'

CodePudding user response:

You can validate nicename as string

 'shop_country' => 'required|string|exists:countries,nicename',

Or validate country id itself

 'country_id' => 'required|integer|exists:countries,id',
  • Related