How do you force a JSON response on every response in Laravel?

后端 未结 6 2051
面向向阳花
面向向阳花 2021-02-13 14:31

I\'m trying to build a REST api using Laravel Framework, I want a way to force the API to always responed with JSON not by doing this manulaly like:

return Respo         


        
6条回答
  •  你的背包
    2021-02-13 15:33

    I know this has been answered but these are not good solutions because they change the status code in unpredictable ways. the best solution is to either add the appropriate headers so that Laravel returns JSON (I think its Accept: application/json), or follow this great tutorial to just always tell Laravel to return JSON: https://hackernoon.com/always-return-json-with-laravel-api-870c46c5efb2

    You could probably also do this through middleware as well if you wanted to be more selective or accommodate a more complex solution.

提交回复
热议问题