MethodNotAllowedHttpException using Form Request Validation on Laravel 5.5

前端 未结 2 2031
隐瞒了意图╮
隐瞒了意图╮ 2020-12-20 08:41

This is pretty strange when i use Form Request Validation on Laravel 5.5, all my post request gonna be 405 Method Not Allowed, but getting normal when i use standard validat

相关标签:
2条回答
  • 2020-12-20 09:21

    when you send the request from insomnia make sure to add the headers;

    accept: application/json and Content-Type: application/json

    that way laravel knows that its an api request and will use routes defined on api.php and not web.php routes.

    0 讨论(0)
  • 2020-12-20 09:23

    The error didn't come from the validation.

    It was because when you use FormRequest class, you are using its default failedValidation method which is for web and redirect to previous page with error. In your case, you are using api but it redirecting to a url that doesn't exists. When you are using standard validation, you are specifying your own logic.

    throw new ValidationException($validator, $this->response(
            $this->formatErrors($validator)
        ));
    

    So, you need to make your custom failed validation approach with your api. You can do something like in your StoreRegistration class, you can override failedValidation method to the following-

    public $validator = null;
    protected function failedValidation(\Illuminate\Contracts\Validation\Validator $validator)
    {
        $this->validator = $validator;
    }
    

    Then your controller method, do anything you want with your $validator object. May be something like the following-

    if (isset($request->validator) && $request->validator->fails()) {
        return response()->json($request->validator->messages(), 400);
    }
    

    Have a look at this link previously I answered.

    0 讨论(0)
提交回复
热议问题