Laravel中使用数组索引(而非键名)进行手动验证
Hey there! Let's work through how to validate that keyless indexed array you're dealing with. It's totally understandable that this feels tricky since Laravel's validation docs focus a lot on associative arrays, but we have a couple of straightforward solutions.
Option 1: Convert to an Associative Array (Recommended)
The cleanest approach is to map your indexed array to an associative one with meaningful keys. This makes your validation rules easier to read, and error messages will be much more intuitive (instead of seeing errors for "index 0", you'll see them for "first_name").
Here's how to do it:
$row = ['John','Doe','john.doe@acme.com','Manager']; // Map the indexed elements to named keys $formattedData = [ 'first_name' => $row[0], 'last_name' => $row[1], 'email' => $row[2], 'position' => $row[3] ]; // Now validate using the named keys $validator = Validator::make($formattedData, [ 'first_name' => 'required|max:2', 'last_name' => 'required', 'email' => 'required|email', // Add email validation since it's an email address 'position' => 'required' ]); // Check if validation failed if ($validator->fails()) { // Access errors like you normally would dd($validator->errors()->all()); }
Option 2: Validate Directly Using Array Indices
If you don't want to reformat the array, you can absolutely use the numeric indices as keys in your validation rules. Your first two attempts were actually correct syntax—maybe you just didn't properly check if the validation failed or inspect the error messages?
Let's test it out:
$row = ['John','Doe','john.doe@acme.com','Manager']; $validator = Validator::make($row, [ 0 => 'required|max:2', // This targets the first element ("John") 1 => 'required' // Targets the second element ("Doe") ]); if ($validator->fails()) { // Errors will be keyed by the numeric index $errors = $validator->errors(); // Example: Get the error for the first element echo $errors->first(0); // Outputs "The 0 must not be greater than 2 characters." }
Note: In this case, "John" is 4 characters long, so the max:2 rule will definitely trigger a validation error—you should see that when you check $validator->fails().
Why Your Third Attempt Didn't Work
The third approach you tried:
$validatedRow = Validator::make($row, [$row[0] => 'required|max:2', $row[0] => 'required']);
This doesn't work because you're using the value of the first element ("John") as a rule key, which doesn't correspond to any key in your original array. Plus, you're using the same key twice, so the second rule overwrites the first—this is never going to target the right element.
内容的提问来源于stack exchange,提问作者Mr Fett

