1

I've got basic laravel validator for my request:

    $validator = Validator::make($request->all(), [
        'speciality' => 'required|array|min:1',
    ]);
    if ($validator->fails()) {
        return response([
            'status' => 'error',
            'error' => 'invalid.credentials',
            'message' => 'error validation'
        ], 400);
    }

speciality should be an array, so I define it as required|array|min:1

The problem is when my request has an empty array with null inside: speciality: [ null ] and this somehow passes my validator.

How can I correct it to catch this case?

1 Answer 1

6

Using dot to access the underlying elements/values:

$validator = Validator::make($request->all(), [
    'speciality' => 'required|array|min:1',
    'speciality.*' => 'required' //ensures its not null
]);

See the Validation: Validating Arrays section of the documentation.


Notice that [null] in not an empty array, that's why your initial validation was passed. You can verify this doing:

dd(empty([null]));

This will output:

false

Sign up to request clarification or add additional context in comments.

2 Comments

@gileneusz just to complement, notice that [null] in not an empty array, that's why your initial validation was passed. You can verify this doing: dd(empty([null]);
@HCK nice catch there. Can you help update the answer with your comment?

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.