Search code examples
phplaravelvalidationlaravel-validationlaravel-5.6

Laravel 5.6 validator on ajax (api route) returns 200 instead of 422


I am posting on Postman to my api route (in api.php) and when the data fails in validation, it returns me the errors in 200 response under this:

enter image description here

The above response is when I try:

{
    $valid = validator($request->only('email', 'password'), [
        'email' => 'required|string|email|max:255|unique:users',
        'password' => 'required|string|min:6',
    ]);

    if ($valid->fails()) {
        $jsonError=response()->json($valid->errors()->all(), 400);
        return \Response::json($jsonError);
    }
}

However, when I try the one in the documentation like below, it returns me to the view (laravel welcome page), something like return back()

 $request->validate([
     'email' => 'required|string|email|max:255|unique:users',
     'password' => 'required|string|min:6',
 ]);

And the data I post is:

email: ''
password: ''

// also tried with and without header
Content-Type: application/json

Solution

  • This code is problematic.

    $jsonError=response()->json($valid->errors()->all(), 400);
    return \Response::json($jsonError);
    

    $jsonError is already a JSONResponse object, then you've encapsulated it again inside a JSONReponse object.

    The json method creates a new JSONResponse object, here is the underlying code.

    public function json($data = [], $status = 200, array $headers = [], $options = 0)
    {
        return new JsonResponse($data, $status, $headers, $options);
    }
    

    So, when you've pass $jsonError here, it was the $data argument. Now, $status argument has a default value of 200, but you DIDN'T pass any, as per your code:

    return \Response::json($jsonError);
    //                               ^-- yeah, no $status argument here!
    

    So it is correct that you will have a 200 response.

    To fix your issue, just return the first JSONResponse object you've created.

    return response()->json($valid->errors()->all(), 400);
    

    If you still want to stick with your current code, then do this. But this is pointless.

    $jsonError=response()->json($valid->errors()->all(), 400);
    return \Response::json($jsonError, 400);
    

    Also, response()->json() is just the same as Response::json() :)