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


How access validation error messages before sending view?

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

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

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

$errors = session('errors');

一旦您有了错误消息包,您可以使用$errors->getMessages()$errors->all()获得消息,以获得一个平面数组。

验证器的消息作为$validator->messages()可用。

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

如果你想发送回要在页面上查看的消息,然后发送它与重定向:

$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();

这是在控制器中访问错误消息的方式。

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