获取列表的索引并在Laravel中验证期间显示错误消息

时间:2016-11-15 04:18:45

标签: php laravel validation laravel-5

我有一个验证规则如下。我通过 ValidateRequests 特征使用验证方法。

$this->validate($request, [
    'entries'                 => 'required|max:5',
    'entries.*.name'          => 'required',
    'entries.*.email'         => 'required|email',
    'entries.*.mobile_number' => 'required'
]);

这些是我遇到的一些示例错误消息。

[
    'entries.0.name'  => ['The entries.0.name is required.'],
    'entries.1.email' => ['The entries.1.email must be a valid email address.']
]

是否有办法在修改此类消息时仅使用validation.php将消息修改为这些消息?

[
    'entries.0.name'  => ['Line 0 - The name is required.'],
    'entries.1.email' => ['Line 1 - The email must be a valid email address.']
]

1 个答案:

答案 0 :(得分:0)

如果要自定义错误消息,则可以执行以下操作:

$validator = Validator::make($request->all(), [
                        'entries'                 => 'required|max:5',
                        'entries.*.name'          => 'required',
                        'entries.*.email'         => 'required|email',
                        'entries.*.mobile_number' => 'required'
                    ]);

$validator->setAttributeNames([
            'entries.*.name'          => 'name',
            'entries.*.email'         => 'email',
            'entries.*.mobile_number' => 'mobile number'
        ]);

$errors = $validation->errors()->all();
foreach ($errors as $key => $error) {
    $errors[$key] = "Line {$key} - $error";
}

// dd($errors);

if($validation->fails()) {
    return redirect()->back()->withErrors($errors());
}