Search code examples
phpvalidationlaravel-5validationrules

Optional custom column rule. Laravel 5 validation rules


I want to amend rules in my API request validation. This request is to update a travel_experience model instance.

These are the current rules:

protected $rules = [
    'city_id'            => 'exists:cities,id',
    'country_id'         => 'exists:countries,id',

Basically I want to make city_id and country_id optional. Which means they might or might not exist in the request, if they exist, they cannot be null and must have an ID value for city or country.

In short, if they don't exist, then there value should remain the same in the DB.


Solution

  • From the documentation:

    protected $rules = [
        'city_id'            => 'nullable|exists:cities,id',
        'country_id'         => 'nullable|exists:countries,id',