Laravel Lumen API Validate Json Array

I have this json array as my request data from API.
Example input:


{
    "name": "Test Bundle",
    "sku": "SKU123",
    "qty_available": "2",
	"items":[
        {
            "sku": "SKU123-1",
            "qty_required": "1",
            "item_price": "32.00"
        },
        {
            "sku": "SKU123-2",
            "qty_required": "1",
            "item_price": "12.00"
        }
    ]
}

Validation in laravel:


// validate request data
        $bundle_data = $this->validate($request, [
            'name' => 'required|string|min:1|max:255',
            'sku' => 'required|string|min:1|max:120',
            'qty_available' => 'numeric|required|min:1',

            // validate each array element if array items
            'items.*.sku' => 'required|string|min:1|max:120',
            'items.*.qty_required' => 'numeric|required|min:1',
            'items.*.item_price' => 'required|regex:/^\d+(\.\d{1,2})?$/'
        ]);

Hope this helped someone else.

Reference: https://stackoverflow.com/questions/42258185/how-to-validate-array-in-laravel

By Keenlio, February 18, 2021

What do you think?

Leave a Reply

Your email address will not be published. Required fields are marked *


4 × seven =

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>