如何在发送视图之前访问验证错误消息?

时间:2015-10-19 16:00:00

标签: php forms validation laravel laravel-5

在Laravel验证失败时,请求将重定向到具有验证$errros的视图。我需要在控制器中访问此消息。访问它们的正确方法是什么?我在验证中使用Request类,因此我无法使用:

$validator = Validator::make(...);
$messages = $validator->messages();

4 个答案:

答案 0 :(得分:1)

假设您在重定向时使用了withErrors,您可以直接从会话中获取错误消息包:

$errors = session('errors');

收到错误消息包后,您可以使用$errors->getMessages()获取消息,或者获取平面数组$errors->all()

答案 1 :(得分:0)

验证者的消息以$validator->messages()提供。

$validator = Validator::make(...);
$messages = $validator->messages();

答案 2 :(得分:0)

如果您想要发回要在页面上查看的消息,请将其与重定向一起发回:

$validator = Validator::make(Input::all(), $rules);
if ($validator->fails()) {
    Session::put('failure_message', 'Failure!');
    return Redirect::to('whateverpage')->withErrors($validator)->withInput(Input::all());

如果你想看看生成了什么消息,首先要创建一些消息来关键:

$messages = array(
    'same'    => 'Your passwords don\'t match.',
    'required' => 'The field ":attribute" is required',
    'alpha'   => 'The field ":attribute" can only contain letters',
    'min'     => 'The field ":attribute" must be ":min" characters or greater.',
);
$validator = Validator::make(Input::all(), $rules, $messages);
$messages = $validator->messages();

答案 3 :(得分:0)

这是在控制器内访问错误消息的方法。

$validator = Validator::make(...);
$validator->errors()->get('date');