如您所料,当验证失败时,我创建了一个重定向。
return Redirect::to('search')->withErrors($v->messages())
我可以在 View 中毫无问题地访问它,但是我想做一些不同的事情。我有一个ErrorPartial.blade.php,我希望将其传递给我的搜索 View 。
return View::make('search.searchForm')
->with('title', 'Search Page')
->with('components', Subject::select('Component')->distinct()->get())
->with('measurementRow',$measurementRow)
->with('races', Race::parseRaceTable())
->with('errorPartial', View::make('errorPartial')
->with('errors',$v->messages())
->render())
;
问题是我无法在此 Controller 功能中访问$ v。我可以某种方式访问将传递给 View 的错误吗?我已经试过了:
return Redirect::to('search')->withErrors($v->messages())
->with('v', $v);
但是我得到这个错误。
Serialization of 'Closure' is not allowed
我可以在搜索 View 中创建部分 View ,但是我想知道他们是否是这样做的一种方式。如果有人知道哪种会更有效或GPP,那么我也不会介意知道这一点。
谢谢
最佳答案
Laravel将错误存储在Session中。
并且Blade中可用的所有功能都来自ViewErrorBag类。
use Illuminate\Support\ViewErrorBag;
...
$errors = session()->get('errors', app(ViewErrorBag::class));
首选此方法,因为如果 session 中没有错误,它将返回空错误包。这意味着您可以在此对象上调用
$errors->any()
,而不会期望出现错误提示Call to a member function any() on null
您始终可以按照以下建议在源代码中找到实现
The
$errors
variable is bound to the view by theIlluminate\View\Middleware\ShareErrorsFromSession
middleware, which is provided by theweb
middleware group. When this middleware is applied an$errors
variable will always be available in your views, allowing you to conveniently assume the$errors
variable is always defined and can be safely used.
Documentation
关于validation - 从重定向Laravel访问 Controller 中的错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23137627/