Laravel validation throwing “NotFoundHttpException

2019-09-19 09:01发布

I am creating an API but stuck debugging.

Using this in my controller method:

$this->validate($request, [
    'project_id' => 'required',
    'content'    => 'required',
]);

If I call that route with PostMan I get a not found error return by Laravel's debugging screen.

However the API call works fine when using an Angular (ionic) $http request.

Any help?

2条回答
forever°为你锁心
2楼-- · 2019-09-19 09:50

https://laravel.com/docs/5.1/validation#form-request-validation
If validation fails, a redirect response will be generated to send the user back to their previous location. The errors will also be flashed to the session so they are available for display. If the request was an AJAX request, a HTTP response with a 422 status code will be returned to the user including a JSON representation of the validation errors.

Checkout the code from FormRequest

public function response(array $errors)
{
    if ($this->ajax() || $this->wantsJson()) {
        return new JsonResponse($errors, 422);
    }

    return $this->redirector->to($this->getRedirectUrl())
                                    ->withInput($this->except($this->dontFlash))
                                    ->withErrors($errors, $this->errorBag);
}

When you use angular, Laravel knows you are sending ajax requests. When using Postman, Laravel thought it's a form request and redirect you to previous page which is 404. The solution is to add a header Accept: application/json in postman requests, so that Laravel knows you wantsJson() or X-Requested-With: XMLHttpRequest so Laravel thinks it's a ajax() request.

查看更多
你好瞎i
3楼-- · 2019-09-19 09:52

You can try the following

$validator = \Validator::make($request->all(), [
   'project_id' => 'required',
   'content'    => 'required',
    ]);

if($validator->fails()){
  return 'Validation error';
}
else{
 return 'No error';
 }
查看更多
登录 后发表回答