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?
Advertisement
Answer
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
SymfonyComponentHttpFoundationResponseclass, which provides a variety of methods for building HTTP responses
for return response()->json() method
The
jsonmethod will automatically set theContent-Typeheader toapplication/json, as well as convert the given array to JSON using thejson_encodePHP function
so this will be recognised as json object in your frontend. Read more at laravel doc.