Laravel: Validate empty array in request

Viewed 2381

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 Answers

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"]
}
Related