1

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',
Owen Kelvin
  • 14,054
  • 10
  • 41
  • 74

2 Answers2

4

you can use present validation

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

 'topics' => 'present|array'
OMR
  • 11,736
  • 5
  • 20
  • 35
  • 1
    Note, that unless you use the `ConvertEmptyStringsToNull` middleware, an empty string can still pass the validation: https://github.com/laravel/framework/issues/18948 – naszy Apr 06 '21 at 19:38
  • thanks @naszy, I did not know that before – OMR Apr 06 '21 at 19:42
3

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.
MrEduar
  • 1,784
  • 10
  • 22
  • 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 – Owen Kelvin Apr 06 '21 at 19:22
  • 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 – Owen Kelvin Apr 06 '21 at 19:24
  • In the examples with photos, there is the solution, however I have updated the answer in your particular case. – MrEduar Apr 06 '21 at 19:31