I am building a bulk-entry form in Laravel where a user can submit multiple items at once. My request data comes in as an array of objects, like items[0][name] and items[0][quantity]. I’m struggling to write the validation rules in my FormRequest—if I just validate 'items' as an array, I can't check the individual attributes inside each index. How do I use the wildcard asterisk (*) notation to ensure every 'name' is a string and every 'quantity' is a minimum of one, while also providing custom error messages for each specific array element?
3 answers
The most effective way to handle this is by using the dot notation with an asterisk in your rules() method. For your specific case, you would define rules like 'items' => 'required|array|min:1', and then target the nested elements with 'items.*.name' => 'required|string|max:255' and 'items.*.quantity' => 'required|integer|min:1'. The asterisk acts as a wildcard that applies the rule to every element within the 'items' array. If you need to ensure that the array itself doesn't contain duplicate values for a specific field, you can even use the distinct rule, such as 'items.*.email' => 'distinct'. This ensures data integrity across the entire batch submission without requiring manual loops in your controller.
If I have an array where the keys are specific strings instead of integers, does the asterisk wildcard still work correctly, or do I need to explicitly define every possible key in my validation array?
For a better user experience, make sure to use the messages() method in your FormRequest. You can use 'items.*.name.required' => 'Each item must have a name' to give specific feedback
I agree with Sarah. Without custom messages, Laravel returns errors like "items.0.name is required," which looks very technical to an end-user. Mapping those to friendly names makes the bulk form much easier to correct when a user misses a single field in a long list.
Trevor, the asterisk wildcard works perfectly for associative arrays too! If your input is data['user_1']['email'], you can just use data.*.email. However, if you have specific keys that require different logic—for example, 'admin' needs different rules than 'editor'—then it is better to skip the wildcard and define them explicitly. For bulk uploads or dynamic forms where you don't know the keys beforehand, the wildcard is definitely your best friend to keep the code DRY and maintainable.