4

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!

3
  • Tip: You can create specific requests to deal with validation, thereby having the controller just deal with the update-logic. Commented May 25, 2020 at 8:02
  • 1
    "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." Commented May 25, 2020 at 8:04
  • You can also look into using the sometimes rule. Commented May 25, 2020 at 8:05

1 Answer 1

6

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"]
}
Sign up to request clarification or add additional context in comments.

4 Comments

I tried your solution, but the 'ids.*' => 'integer' rule is ignored, if i put in the "present". Is there a way to combine these to rule, to have a propert validation?
What do you mean "ignored"? Are you saying you can add strings instead of integers and the validation fails?
Sorry for the late answer. When I leave the "'ids.*' => 'integer'" Validation, I can pass An array of strings, and the validation does not fail
@Febertson That sounds really odd. Could you try and remove the try/catch? It's a weird construction and not something that is encouraged.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.