Ad

Which One Should I Use?

- 1 answer

I am building this website application using Laravel 6 and React Native for the mobile app. The question is:

Should I use

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

or return $products->toJson();

Which one should I use to fetch the data from my Laravel 6 back end application to the React Native app?

Ad

Answer

Both the methods are correct. Laravel will automatically convert anything you pass as return of a controller method to a Illuminate\Http\Response object, so you can return:

  • Booleans
  • Strings (including JSON strings)
  • Arrays
  • Responses
  • JsonResponses

When you use response() it allows you setting response code and headers. Returning directly the json you won't be able to do that.

Ad
source: stackoverflow.com
Ad