Laravel Validator如何验证数组长度与另一字段值匹配?
The issue here is that when you use size:numItems, Laravel treats "numItems" as a literal string instead of referencing the actual value of the numItems field in your request. It’s trying to check if the items array has exactly 7 elements (the length of the string "numItems") instead of matching the integer value from numItems.
Here are two straightforward ways to fix this validation:
Solution 1: Use the Rule facade with dynamic size
Leverage Laravel’s Rule facade to pass the real value of numItems to the size rule. Add the bail rule to numItems to stop validation early if numItems is invalid (like a non-integer), preventing issues with non-numeric values:
use Illuminate\Validation\Rule; public function yourValidationMethod(Request $request) { $validated = $request->validate([ 'numItems' => 'required|int|max:10|bail', 'items' => [ 'required', 'array', Rule::size($request->numItems), ], ]); // Process your validated data here }
Solution 2: Custom validation closure
For full control over the error message or extra logic, use a custom validation closure. This lets you directly compare the count of items to the numItems value:
public function yourValidationMethod(Request $request) { $validated = $request->validate([ 'numItems' => 'required|int|max:10', 'items' => [ 'required', 'array', function ($attribute, $value, $fail) use ($request) { $expectedCount = (int)$request->numItems; if (count($value) !== $expectedCount) { $fail("The {$attribute} must contain exactly {$expectedCount} items."); } }, ], ]); // Process your validated data here }
A quick note on your JSON structure: The example you provided has an invalid array format for items (JSON arrays can’t include key-value pairs like "1": {...}). You likely want either an array of objects:
{ "numItems": 3, "items": [ {"A": "Foo", "B":"bar"}, {"A": "Foo", "B":"bar"}, {"A": "Foo", "B":"bar"} ] }
Or an object with numeric keys:
{ "numItems": 3, "items": { "1": {"A": "Foo", "B":"bar"}, "2": {"A": "Foo", "B":"bar"}, "3": {"A": "Foo", "B":"bar"} } }
Either structure will work correctly with the validation logic above.
内容的提问来源于stack exchange,提问作者MikeVelazco

