2

The documentation says:

The json method will automatically set the Content-Type header to application/json

But if I have a route in api.php or web.php and return an array in it, that header is also put.

Route::get('test', function () {
    return [
        'test' => 'test'
    ];
});

enter image description here

Does it make sense to write extra code response()->json(...) if you can do so?

2
  • 1
    Yes it does make sense, for whoever is reading the code after you. I bet that when you send a request with a header accept: application/json Laravel will try to return JSON. It may be the case that if you return "non HTML" (no view()) it tries to convert to JSON. Commented Sep 18, 2018 at 8:38
  • when we are sending post json data in an api. In laravel we will get it as an array because it is post request and we will get it as $request->all(). Commented Sep 18, 2018 at 8:51

1 Answer 1

2

I think it depends on you. When ever you return any value that is like collection and arrays, Laravel automatically transforms it as JSON (I have never noticed the application/json header though) and also with this is status code 200.

The implication is if you don't want Laravel to set the header for you and also the status code then use, response()->json([...], status_code_here).

Sign up to request clarification or add additional context in comments.

1 Comment

Relevant Laravel documentation entry: laravel.com/docs/9.x/responses#strings-arrays

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.