Laravel 4 将错误消息注入错误对象

Laravel 4 将错误消息注入错误对象,laravel-4,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

有没有一种方法可以插入错误消息,这样我们就可以在重定向时在带有
$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

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

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

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

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

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