3

I am trying to apply the suggestions provided in this question How to validate array in Laravel?

So my validation is

'topics' => 'required|array'

Topics are required

This works well especially if topics is an array greater than 1

unfortunately is I pass [] an empty array the validation fails

How can I validate that the input is an array, Its not null and empty array is allowed?

Below attempt fails

 'topics' => 'required|array|min:0',

Topics are required

Below works, the problem is that even null values are permitted

 'topics' => 'array',
1
  • What's about 'topics' => 'nullable|array' Commented Apr 6, 2021 at 19:55

2 Answers 2

6

From the Laravel documentation:

Validating array based form input fields doesn't have to be a pain. You may use "dot notation" to validate attributes within an array. For example, if the incoming HTTP request contains a photos[profile] field, you may validate it like so:

use Illuminate\Support\Facades\Validator;

$validator = Validator::make($request->all(), [
    'photos.profile' => 'required|image',
]);

You may also validate each element of an array. For example, to validate that each email in a given array input field is unique, you may do the following:

$validator = Validator::make($request->all(), [
    'person.*.email' => 'email|unique:users',
    'person.*.first_name' => 'required_with:person.*.last_name',
]);

In your case, if you want to validate that the elements inside your array are not empty, the following would suffice:

'topics' => 'required|array',
'topics.*' => 'sometimes|integer', // <- for example.
Sign up to request clarification or add additional context in comments.

4 Comments

Thanks for the answer, What I have picked from your answer is how to validate each individual element but my problem is not the individual elements. The issue is that null is validated as okay but if I add required not validation fails even for empty array
In simple terms, I would like a way to validate that the request is not null and the request is either an empty array or an array with values
In the examples with photos, there is the solution, however I have updated the answer in your particular case.
When copying and pasting from a source, ensure you indicate what you have copied and from where. Otherwise you risk your account being flagged for plagiarism.
4

you can use present validation

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

 'topics' => 'present|array'

2 Comments

Note, that unless you use the ConvertEmptyStringsToNull middleware, an empty string can still pass the validation: github.com/laravel/framework/issues/18948
thanks @naszy, I did not know that before

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.