Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

Thavo's avatar
Level 2

Laravel 8 API response request validation status 200

Hello, Laravel - 8.x PHP 7.4

I'm using api routes and also request validation However when the request fail, laravel is returning error 200 and welcome view

USER STORE REQUEST:
public function rules()
    {
        return [
            'name' => 'required|max:100',
            'email' => 'required|email|unique:users,email',
            'password' => 'required|max:50',
        ];
    }

// My controller method
public function store(UserStoreRequest $request)
  {
			// This fail the request and return status 200

    try {
      $this->repository->create($request);

      return response()->json(['message' => 'User created!'], 201);
    } catch (\Throwable $th) {

      return response($th->getMessage(), 400);
    }
  }

If I send a post here with wrong params I got status 200 like this print: https://prnt.sc/1ru7n1u I should got status code 422

What should I do to return the correct status code with validation error message?

0 likes
8 replies
frankielee's avatar

Set the Header to accept only 'application/json' format as response.

Also, please show the UserStoreRequest file, did you always return true at the function authorize?

1 like
Thavo's avatar
Level 2

@frankielee yes authorize is true I added a middleware to only accept json however I got this error: https://prnt.sc/1ru9697

What am I doing wrong?

// MIDDLEWARE
public function handle($request, Closure $next)
    {
        // Verify if POST request is JSON
        if ($request->isMethod('post') && !$request->expectsJson()) {
            return response(['message' => 'Only JSON requests are allowed'], 406);
        }

        return $next($request);
    }
frankielee's avatar

@Thavo How about this?

Set the Header to accept only 'application/json' format as response.

frankielee's avatar
Level 29

@Thavo You set the wrong key at the header.

Change the "content-type" to "Accept"

frankielee's avatar

@Thavo

Content-Type is the format you sent to the request.

Accept is you only accept the response in JSON format.

But accept only works if the framework/application is handling such things.

Please or to participate in this conversation.