I'm getting into api controllers
and am wondering if this index function
:
public function index()
{
$data = DB::table('galleries')->get();
return response()->json($data);
}
inside my api controller
has to be returned with response()->json()
or if it is OK to just return the variable:
public function index()
{
$data = DB::table('galleries')->get();
return $data;
}
Both seem to work. Are there reasons to use the former one?
CodePudding user response:
the return $data
will just convert the $data
into a json response. no header will be set and your frontend will not recognize it as a json object.
return response()
will return a full Response
instance. from the doc
Returning a full Response instance allows you to customize the response's HTTP status code and headers. A Response instance inherits from the
Symfony\Component\HttpFoundation\Response
class, which provides a variety of methods for building HTTP responses
for return response()->json()
method
The
json
method will automatically set theContent-Type
header toapplication/json
, as well as convert the given array to JSON using thejson_encode
PHP function
so this will be recognised as json object in your frontend. Read more at laravel doc.
CodePudding user response:
Both seem , both are correct but if you send as json it will be formal and in the fornt-end site they can use easily
CodePudding user response:
When you send something as a response which is not already an instance of a Response
then Laravel will create a new instance of a Response
with that as the content. When the response is sent and that object is an array (or arrayable) or something that is convertible to JSON then it is sent as a JSON response. At that point all relevant headers will be correct.
There are two parts of the source code to consider if you are curious on how this works:
- The part that checks whether the response is already an instance of
Response
and constructs one if not - The part that decides whether a response content should be JSON
If you want my opinion then you should be doing response()->json(...)
which creates a JsonResponse
instance that has no chance to be ambiguous because otherwise you are relying on undocumented behavior which is subject to change.