我在让 ->withInput() 和 ->withErrors() 工作时遇到问题,以便在验证失败时我可以在刀片中检索它们。这就是我在控制器中的内容:$rules = array( 'mobile' => 'required');$validator = Validator::make($request->all(), $rules);if ($validator->fails()) { $fieldsWithErrorMessagesArray = $validator->messages(); $fieldsWithErrorMessagesArray = $fieldsWithErrorMessagesArray->messages(); $formattedErrorArray = array(); foreach ($fieldsWithErrorMessagesArray as $key => $error) { $formattedErrorArray[$key] = $error[0]; } return redirect()->back()->withInput()->withErrors($formattedErrorArray);}但是在刀片中,当 var_dump $errors 时,我得到了这个:object(Illuminate\Support\ViewErrorBag)#267 (1) { ["bags":protected]=> array(0) { } }如果我要 dd($fieldsWithErrorMessagesArray),它会给我:array:7 [▼ "mobile" => array:1 [▼ 0 => "The mobile field is required." ]]我也试过这种方式:$test = array( 'mobile' => 'No jobs found. Please try searching with different criteria' );return redirect()->back()->withInput()->withErrors($test);这行得通,我不确定为什么另一个不起作用。使用这个测试数组,刀片文件看起来像这样:object(Illuminate\Support\ViewErrorBag)#264 (1) { ["bags":protected]=> array(1) { ["default"]=> object(Illuminate\Support\MessageBag)#265 (2) { ["messages":protected]=> array(2) { ["mobile"]=> array(1) { [0]=> string(59) "No jobs found. Please try searching with different criteria" }} ["format":protected]=> string(8) ":message" } } }
1 回答

吃鸡游戏
TA贡献1829条经验 获得超7个赞
为什么不直接使用“自动重定向”:
$validator = Validator::make($request->all(), array(
'mobile' => 'required'
));
$validator->validate(); // automatically redirects if validation fails
validate您可以在现有验证器实例上调用该方法。如果验证失败,将自动重定向用户。
这是完整的文档:https ://laravel.com/docs/master/validation#automatic-redirection
注意 1:确保Illuminate\View\Middleware\ShareErrorsFromSession中间件列在您的web中间件组中\app\Http\Kernel.php(完整文档)。
注意 2:Laravel 将检查会话数据中的错误,因此请检查会话驱动程序\config\session.php和要设置SESSION_DRIVER的文件属性。.env尝试不同的驱动程序并检查它是否有效。
- 1 回答
- 0 关注
- 89 浏览
添加回答
举报
0/150
提交
取消