orest
1 month ago
138
2
General

Json response confusion

Posted 1 month ago by orest

Hi,

I'm trying to understand the following concepts:

  1. Laravel automatically converts arrays, collections, model to json
  2. toJson()
  3. response()->json()

According to laravel's documentation, laravel converts automatically arrays and collections to json format and adds to the header the content-type to be equal to application/json. Therefore, from what i understand, whenever you want to return a single row or a collection of rows from the database to the front-end, there is no need to convert anything to json, because laravel takes care of that.

But then i also read on laravel's documentation the following

'To convert a model to JSON, you should use the toJson method.'

The only difference that i noticed when i called this method is that the content-type actually is not 'application/json' but 'text-html'.

Please sign in or create an account to participate in this conversation.