向错误对象注入错误消息

时间:2014-05-05 07:08:34

标签: laravel-4

有没有办法注入错误消息,以便我们可以在重定向上使用$errors实例在视图上显示它?

$errors->all(); // e.g. to have it here

我试过了:

return Redirect::to('dashboard')
                    ->with('errors', 'Custom error');

但实际上会抛出错误:

Call to a member function all() on a non-object

2 个答案:

答案 0 :(得分:4)

您的示例不起作用,因为您只传递变量而不是对象。

如果要将自己的自定义错误消息添加到其他验证错误,可以使用add()类的Illuminate\Support\MessageBag方法(因为验证错误将作为此类的实例返回):< / p>

$validator = Validator::make($data, $rules);

if ($validator->fails()) {
    $errors = $validator->messages();
    $errors->add('Error', 'Custom Error');

    return Redirect::to('dashboard')->withErrors($errors);
}

现在,您的自定义消息应与其他验证错误一起显示。

答案 1 :(得分:1)

简单的一线解决方案

虽然kajetrons said完全正确,但如果您只想通过$errors对象返回错误消息,则无需创建验证程序。这可以更简单地写在一行:

return Redirect::to('dashboard')->withErrors(new \Illuminate\Support\MessageBag(['Custom error']));