Laravel: Set the Content-Type header to application/json

July 16, 2022  ‐ 1 min read

The Content-Type header is added to responses to indicate the MIME type of the response data. For JSON API's the MIME type to return is application/json.

In Laravel we can use the header() method to the response object, which allows us to set the Content-Type header to application/json.

return response()->header('Content-Type', 'application/json');

A quicker way is to use the json() method which sets this header for you.

return response()->json($data);

If this doesn't yield the expected content type, your middleware might interfere.