2
votes

In my Laravel application im trying to validate the body of my request, but one specific situation throws a ValidationException.

My code looks like this:

public function updateData(Request $request){
    try {
        $validatedData = $request->validate([
            'ids' => ['required', 'array'],
            'ids.*' => 'integer'

        ]);
    catch (ValidationException $th) {
        return response()->json($this->createFailedResult($th->errors()));
    }
}

The Data I pass looks like this:

No Exception:

{
    ids: [1]
}

With Exception:

{
    ids: []
}

Thats the Ecception:

[ids] => Array ( [0] => The ids field is required. ) )

I've read about exchanging "required" with "present", but i dont want empty strings to be ignored by the validation.

Thanks for your help!

1
Tip: You can create specific requests to deal with validation, thereby having the controller just deal with the update-logic. - Qirel
"Required" means that there MUST be a value there. present means that it will be required in the input, but can be empty. From the manual on "present", "The field under validation must be present in the input data but can be empty." - Qirel
You can also look into using the sometimes rule. - Qirel

1 Answers

2
votes

I've read about exchanging "required" with "present", but i dont want empty strings to be ignored by the validation.

The present validation rule requires the presence of the field.

A valid request with present|array contains one of the following:

{
    "ids": []
}
{
    "ids": [1, 2, 3]
}

If the validation rule was required|array, only the latter is valid.

By extending your validation rule with 'ids.*' => 'integer', you ensure that the provided input, if given any, is validated as integers. Therefore, the following would not be valid, even though the ids field is present:

{
    "ids": ["", "ipsum"]
}