在 Laravel 中进行验证时出现 MethodNotAllowedHttp

以下是我的刀片:


<form action="{{route('ans1.eval')}}" method="post">

    <br>

    <input type="radio" name="evaluate" class="evaluate" value=10> 1   &nbsp; &nbsp;

    <input type="radio" name="evaluate" class="evaluate" value=15> 1.5 &nbsp; &nbsp;

    <input type="radio" name="evaluate" class="evaluate" value=20> 2   &nbsp; &nbsp;

    <input type="radio" name="evaluate" class="evaluate" value=25> 2.5 &nbsp; &nbsp;

    <input type="radio" name="evaluate" class="evaluate" value=30> 3   


    <button type="submit" class="btn btn-primary" align="right">Evaluate Answer</button>

    <input type="hidden" value="{{ Session::token() }}" name="_token">

</form>

以下是我的路线:


Route::post('/evaluateans', [

    'uses' => 'AnswerController@postEvaluateAns',

    'as' => 'ans1.eval',

    'middleware' => 'auth'

]);

以下是我的验证:


public function postEvaluateAns(Request $request)

{

    $this->validate($request, [

          'evaluate' => 'required'

    ]);

}


以下是未选择评估时的错误:


MethodNotAllowedHttpException in RouteCollection.php line 218


哆啦的时光机
浏览 209回答 1
1回答

潇潇雨雨

来自关于验证的 laravel 文档如果验证规则通过,您的代码将继续正常执行;但是,如果验证失败,则会抛出异常,并自动将正确的错误响应发送回用户。在传统 HTTP 请求的情况下,将生成重定向响应。当您的验证失败时,它会使用一个方法重定向回来GET(重定向使用该GET方法),但是如果您显示的formfrom aroute不是GET一个,则会引发此错误。所以你必须用路线显示表格GET。作为替代方案,您可以手动创建验证器,以便GET在验证失败时选择重定向路由,例如:public function postEvaluateAns(Request $request){&nbsp; &nbsp; $validator = Validator::make($request->all(), [&nbsp; &nbsp; &nbsp; &nbsp; 'evaluate' => 'required'&nbsp; &nbsp; ]);&nbsp; &nbsp; if ($validator->fails()) {&nbsp; &nbsp; &nbsp; &nbsp; return redirect('failed_validation_GET_route')&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; ->withErrors($validator)&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; ->withInput();&nbsp; &nbsp; }&nbsp; &nbsp; return redirect()->route('success_GET_route')&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;->with('status', 'Success!');}
打开App,查看更多内容
随时随地看视频慕课网APP