Guillem Poy
Guillem Poy

Reputation: 811

Array validation fails with Laravel API (but I am sending an array)

I have an API built with Laravel. It does the following validation:

        $validator = Validator::make($request->all(), [
            'product_ids' => 'required|array',
            'product_ids*' => 'required|exists:products,id',
            'product_quantities' => 'required|array',
            'product_quantities*' => 'numeric',
        ], [
            'order_type.in' => trans('validation.order_type'),
        ]);

I am sending the following data in the request: enter image description here

As text:

product_ids:[697,339]
product_quantities:[3,1]

However, I get as a response, 422:

{
  "errors": {
    "product_ids": [
      "The product_ids must be an array."
    ],
    "product_quantities": [
      "The product_quantities must be an array.",
      "The product_quantities must be a number."
    ]
  }
}

The same results appear using postman, thunder client and uno (dart). However, it works if I use axios (JS) with the same apparent data.

Any clue why the data I send is not always recognized as an array?

Upvotes: 0

Views: 627

Answers (2)

zohrehda
zohrehda

Reputation: 643

There is a difference in validation of an array parameter and elements in the array parameter:

$validator = Validator::make($request->all(), [ 
  'product_ids' => 'required|array',
  'product_ids.*' => 'required|exists:products,id', 
  'product_quantities' => 'required|array',
  'product_quantities.*' => 'numeric'
], ['order_type.in' => trans('validation.order_type')]);

You need to put a . between the array parameter and *. That refers to elements in the array.

Upvotes: 0

Abdulla Nilam
Abdulla Nilam

Reputation: 38652

The request should be passed as an object when you pass data as an array.

In Postman/AJAX/JS

'Content-Type': 'application/json'

JSON.stringify(); # for async  request

Example

sendProductIds(productIds) {
    body: JSON.stringify({ product_ids: productIds })
}

sendProductIds([1, 2, 3]);

And Validation should be

$validator = Validator::make($request->all(), [
    'product_ids' => 'required|array',
    'product_ids.*' => 'integer|exists:products,id',
]);

Upvotes: 1

Related Questions