user947668
user947668

Reputation: 2728

Laravel filled validation rule for array element

I need to check input array of strings and raise warning if at least one of array elements is empty.

The following rule is used:

return Validator::make($data, [
    'branches'         => 'array',
    'branches.*'       => 'filled|max:255'
    ]);

However it seems filled rule doesn't work (while min:1 works fine). Should it work with array elements or not?

UPDATE: branches array is not mandatory, but if exists it should contain non empty elements.

UPDATE: Finally found mistake in my validation rule. It should look like

return Validator::make($data, [
    'branches'         => 'array',
    'branches.*.*'       => 'filled|max:255'
    ]);

since input array is array of arrays. Now filled rule works as expected with my input data.

Upvotes: 6

Views: 7201

Answers (2)

Mr. Pyramid
Mr. Pyramid

Reputation: 3935

Considering your comment you should try nullable

return Validator::make($data, [
    'branches'         => 'nullable|array',
    'branches.*'       => 'nullable|max:255'
]);

OR

You can use presentthis will ensure that array should be passed either with values or just an empty array

return Validator::make($data, [
    'branches'         => 'present|array',
    'branches.*'       => 'nullable|max:255'
]);

Upvotes: 2

Lars Mertens
Lars Mertens

Reputation: 1439

Use required instead

return Validator::make($data, [
    'branches'         => 'required|array',
    'branches.*'       => 'required|max:255'
]);

From the documentation: https://laravel.com/docs/5.5/validation#available-validation-rules

required

The field under validation must be present in the input data and not empty. A field is considered "empty" if one of the following conditions are true:

  • The value is null.
  • The value is an empty string.
  • The value is an empty array or empty Countable object.
  • The value is an uploaded file with no path.

If you want to validate the array only if there is field data present use filled. You can combine this with present.

return Validator::make($data, [
    'branches'         => 'present|array',
    'branches.*'       => 'filled|max:255'
]);

filled

The field under validation must not be empty when it is present.

present

The field under validation must be present in the input data but can be empty.

Upvotes: 5

Related Questions