1
votes

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',
2
What's about 'topics' => 'nullable|array'Espresso

2 Answers

2
votes

you can use present validation

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

 'topics' => 'present|array'
1
votes

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.