Orkhan Orkhan
Orkhan Orkhan

Reputation: 105

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?

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

Upvotes: 0

Views: 344

Answers (4)

Mahmoud Mohamed
Mahmoud Mohamed

Reputation: 21

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',

Upvotes: 0

Nazgot
Nazgot

Reputation: 422

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'

Upvotes: 0

ThS
ThS

Reputation: 4783

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.

Upvotes: 0

You can define it as:

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

See docs

Upvotes: 1

Related Questions