Laravel 重定向输入和错误不起作用

我在让 ->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" } } }


慕妹3242003
浏览 90回答 1
1回答

吃鸡游戏

为什么不直接使用“自动重定向”:$validator = Validator::make($request->all(), array(   'mobile' => 'required'));$validator->validate(); // automatically redirects if validation failsvalidate您可以在现有验证器实例上调用该方法。如果验证失败,将自动重定向用户。这是完整的文档: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尝试不同的驱动程序并检查它是否有效。
打开App,查看更多内容
随时随地看视频慕课网APP