You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Laravel中使用数组索引(而非键名)进行手动验证

Validating Indexed Arrays in Laravel 8

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.

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.30 08:27:41