我在让 ->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" } } }
吃鸡游戏