Skip to content
Advertisement

Do all API responses need to explicitly be returned with a json function?

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 SymfonyComponentHttpFoundationResponse class, which provides a variety of methods for building HTTP responses

for return response()->json() method

The json method will automatically set the Content-Type header to application/json, as well as convert the given array to JSON using the json_encode PHP function

so this will be recognised as json object in your frontend. Read more at laravel doc.

User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement