skip to Main Content

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?

2

Answers


  1. There is difference in validation of a 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 reffers elements in the array.

    Login or Signup to reply.
  2. 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',
    ]);
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search