Yansen Tan
Yansen Tan

Reputation: 551

Validate 2nd Level Array/JSON using Laravel Validator

Let say I have this JSON request to my Laravel Route

{
    "user_id":1,
    "payment_type":"point",
    "order_boxes":[
        {
            "for_friend_name":"Yansen",
            "order_box_items":[
                {
                    "product_id": 1,
                }    
            ]
        }    
    ]
}

I can validate the request up to "order_boxes" array level using Laravel Validator using this code :

$rules = [
            'user_id' => 'required|exists:users,id',
            'payment_type' => 'required|in:point,cod,transfer,credit_card',
            'order_boxes' => 'required|array',
        ];

        $validator = Validator::make($request->all(), $rules);
        $validator->each('order_boxes',[
            'for_friend_name' => ['max:25'],
            'order_box_items' => ['required','array']
        ]);

As you can see for the "order_box_items" which inside the "order_boxes", I add another "array" rules and try to validate the array again. And I add this code below :

$validator->each('order_box_items',[
    'product_id' => ['required','exists:products,id']
]);

But it returns "Attribute for each() must be an array".

So I believe the $validator->each() can only validate the first level of the array only. Any idea on how to validate the second level of the array using it?

Thank you

Upvotes: 0

Views: 1242

Answers (2)

Vladislav Rastrusny
Vladislav Rastrusny

Reputation: 30013

This feature will be added in Laravel 5.2. Until then use solutions like @YansenTan posted.

Upvotes: 1

Yansen Tan
Yansen Tan

Reputation: 551

I managed to validate the nested array by using "foreach":

$rules = [
    'user_id' => 'required|exists:users,id',
    'payment_type' => 'required|in:point,cod,transfer,credit_card',
    'order_boxes' => 'required|array',
];

foreach($request->input('order_boxes') as $key => $value){
    $rules['order_boxes.'.$key.'.for_friend_name'] = 'max:25';
    $rules['order_boxes.'.$key.'.order_box_items'] = 'required|array';

    foreach($request->input('order_boxes')[$key]['order_box_items'] as $item_key => $item_value){
        $rules['order_boxes.'.$key.'.order_box_items.'.$item_key.'.product_id'] = 'required|exists:products,id';
    }
}

Upvotes: 0

Related Questions