Laravel validation for checking if value exists in the database

Laravel validation for checking if a field value exists in the database.

The validation rule to use is exists() where you can state the table and column for the value to be found.

$request->validate([
    'country' => [
        'required',
        'string',
        Rule::exists('countries', 'name')
    ]
]);

In the example above the country will be searched in the name column in the countries table. This is also alongside the country field being required and of string format.

You can also add a where conditional onto the query:

$request->validate([
    'country' => [
        'required',
        'string',
        Rule::exists('countries', 'name')->where('continent', 'Asia'),
    ]
]);

This now validates that the country also has the value ‘Asia’ in the continent column.