How to validate if an input field exists in the Laravel database, but can also be empty?

I need to validate an input field, which can be null, but if it’s not empty or null, it must exist in another table in the database. How can I perform this validation in Laravel?

I have a “vehicles” table and a “vehicle_models” table. The “vehicles” table has a column called “vehicle_model_id,” which is linked to the “vehicle_models” table. If “vehicle_model_id” is not null, it must correspond to a valid entry in the “vehicle_models” table. How can I perform this validation using Laravel’s validate method?

Here is my current code:

$request->validate([
    'vehicle_model_id'  => 'exists:vehicle_models,id'
]);

You are almost correct, just put a nullable in front of the validation.

$request->validate([
    'vehicle_model_id'  => 'nullable|exists:vehicle_models,id'
]);

The validation should look like this.