Validating Nested Arrays in Laravel Requests
When validating incoming JSON payloads, handling a single nested object is straightforward using the dot syntax on your validation rules. However, requirements often shift to accommodate multiple entities within a single field. Consider a scenario where you need to validate a skus array containing multiple stock units for a product. The challenge lies in ensuring that every item within that collection adheres to the same strict schema while maintaining the flexibility of Laravel's validation engine.
To handle this, you must modify your rule definition to target the array index rather than the root key directly. Instead of defining rules against skus, you define them against skus.*. This tells the validator to apply the specified constraints to every element found in the skus collection.
Here is how the updated rules should look:
protected $rules = [
ValidatorInterface::RULE_CREATE => [
'categories_id' => 'required',
'product_name' => 'required|max:100',
'product_description' => 'required|max:1000',
'tags' => 'required',
'image_count' => 'required|integer',
// Apply rules to every item in the skus array
'skus.*.is_shippable' => 'in:y,n',
'skus.*.actual_price' => 'regex:/^\s*(?=.*[1-9])\d*(?:\.\d{1,2})?\s*$/',
'skus.*.selling_price' => 'regex:/^\s*(?=.*[1-9])\d*(?:\.\d{1,2})?\s*$/',
// Handle conditional logic within the nested array
'skus.*.quantity_type' => 'sometimes|required|in:finite,infinite,bucket',
'skus.*.quantity_total' => 'integer|required_if:skus.*.quantity_type,finite',
'skus.*.bucket_value' => 'in:instock,soldout,limited|required_if:skus.*.quantity_type,bucket',
'skus.*.sort_order' => 'required|integer'
],
];
The syntax skus.* effectively expands to check each object inside the array. If you submit a request with two SKU objects, Laravel will validate both against these rules. If either object fails validationâfor example, if one has an invalid price formatâthe entire request is rejected, and the error message will indicate which specific item failed (e.g., skus.0.selling_price).
A critical detail to observe involves conditional validations like required_if. When used with nested arrays, the dot syntax must be precise. In the example above, required_if:skus.*.quantity_type,finite ensures that if any SKU in the array has a quantity_type of finite, then that specific SKU's quantity_total must exist and be an integer. This maintains data integrity across the collection without requiring complex custom validation logic.
Another consideration is the presence of the skus key itself. Since the original request example showed skus as a nested object that could become an array, you must decide whether the field is required or optional. If the API allows creating a product without any SKUs, add sometimes to the root skus rule:
'skus' => 'nullable|array',
If skus is always required, simply omitting it from the nullable list ensures the validator checks for its existence before iterating over the array.
Finally, remember that validation rules are static; they do not know about the data structure of your database or how you intend to store the nested arrays. While this approach covers the immediate validation needs, you must ensure your controller logic correctly maps the validated skus array into your model attributes. If using a relationship, you might need to iterate over the validated input to instantiate multiple child models or update an existing collection.
For more complex scenarios involving deeply nested structures or custom validation callbacks, Laravel offers the validateNested method on the request instance, which allows passing a separate validator for a specific key. However, for standard dot-syntax rules like those shown here, the skus.* pattern is the most concise and performant solution for handling collections in API inputs.