Tharindu
Tharindu

Reputation: 339

How to add validation for nested Array of objects

I'm validating my API request in Laravel controller. It consists of an array of objects that each of the item needed to be validated.

I tried the nested array validation and tried creating a separate request validation class but was not able to succeed.

{
    "total" : 250.00,
    "merchant_id" : 1,
    "discount" : 0,
    "items" :  {
        [id: 1, quantity: 25, notes: "some string A"],
        [id: 2, quantity: 10, notes: "some string B"],
        [id: 3, quantity: 5, notes: "some string C"]
    }
}

Each parameter of the main object (total, merchant_id, discount) and also the nested array parameters (id, quantity, notes) needed to be validated

Upvotes: 0

Views: 379

Answers (2)

Amirsadjad
Amirsadjad

Reputation: 515

Let's say all of them are required. you can validate it like this:

$validator = Validator::make($request->all(), [
    'total' => 'required',
    'merchant_id' => 'required',
    'discount' => 'required',
    'items.*.id' => 'required',
    'items.*.quantity' => 'required',
    'items.*.notes' => 'required',
]);

Upvotes: 1

PtrTon
PtrTon

Reputation: 3835

Use the .* notation as specified in https://laravel.com/docs/5.8/validation#validating-arrays

Upvotes: 3

Related Questions