Php – Laravel validation required|exists with exception of 0

laravellaravel-5phpvalidation

HTML form has select dropdown with list of existing categories and no category with id=0.
CategoryStoreRequest must check if the category_id from the form belongs to existing category or is 0

Something like that

public function rules() {
    return [
        "name" => "required|min:3",
        "category_id" => "required|exists:categories,id,except_if_value_is_0"
    ];
}

What is the most elegant way to achieve it?

Best Solution

It turns out that nullable is one quite elegant way to do it. When submitting the form then category_id array key is still present but its value is null. nullable allows the key to be null also.

public function rules() {
    return [
        "name" => "required|min:3",
        "category_id" => "nullable|exists:categories,id"
    ];
}

In addition the select value must be ""

<select name="category_id">
    <option value="">No category selection</option>
    <option value="1">Cat 1</option>
</select>