When you're into making an API, you may wish to make the format of the responses you provide dynamic. If you're not using controllers, you would make a class, but if you use controllers, it's a pretty good idea to place it in the base controller. As well you may restructure your response data to include more fields, e.g. for testing purposes you may wish to also include some custom debug.
// BaseController.php
protected function response($data, $code = 200) {
// Make your own structure of the response
if (!isset($data['success'])) $data['success'] = true;
$data['code'] = $code;
// TODO: make it run only in development/staging
if (App::environment() == 'testing') {
$data['debug_log'] = Environment::getDebug();
$data['debug_sql_count'] = count(Environment::getSql());
$data['debug_sql_queries'] = Environment::getSql();
$data['debug_sql_queries_full'] = Environment::getSql(true);
}
if (Input::has('format') && Input::get('format') == 'xml') {
// convert to xml using your favorite library and print out
} else {
return Response::json($data, $code);
}
}
// In all your controllers actions simply call this method
return $this->response([
'message' => "hello world",
'data' => $data
]);