Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel validation required|exists with exception of 0

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?

like image 649
Margus Pala Avatar asked Jun 14 '17 09:06

Margus Pala


4 Answers

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>
like image 158
Margus Pala Avatar answered Nov 02 '22 22:11

Margus Pala


you can create new validation to handle see this example: in your_project_name/app/providers/AppServicesProviders.php

Validator::extend(
        'exists_or_null',
        function ($attribute, $value, $parameters)
        {
            if($value == 0 || is_null($value)) {
                return true;
            } else {
                $validator = Validator::make([$attribute => $value], [
                    $attribute => 'exists:' . implode(",", $parameters)
                ]);
                return !$validator->fails();
            }
        }
    );

in your example do that

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

}

like image 37
Omar Farag Avatar answered Nov 02 '22 23:11

Omar Farag


You can use sometimes. In this case, the rule will only be applied if a filled category_id is submitted.

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

Change your html, so that there's no value set:

<select name="category_id">
    <option value="">No category selection</option>
    <option value="1">Cat 1</option>
</select>
like image 44
schellingerht Avatar answered Nov 02 '22 22:11

schellingerht


Instead of checking for exists or 0, you could set your custom zero value to NULL or an empty string.

You need to change a little bit of your logic, but then you can validate it correctly by using the sometimes rule:

public function rules() {
    return [
        "name" => "required|min:3",
        "category_id" => "sometimes|exists:categories,id"
    ];
}
like image 29
manniL Avatar answered Nov 03 '22 00:11

manniL