Actually Laravel checks the content of every response before returning it in that very method you are using in your last code block ($response->setContent()).
// This happens in setContent()
if ($this->shouldBeJson($content))
{
$this->headers->set('Content-Type', 'application/json');
$content = $this->morphToJson($content);
}
And the method that determines if the response should be JSON looks like this:
protected function shouldBeJson($content)
{
return $content instanceof JsonableInterface ||
$content instanceof ArrayObject ||
is_array($content);
}
So if you are returning something that implements JsonableInterface (like an Eloquent Model or Collection), is an ArrayObject or a php array they will be converted to JSON for you.
So for example if your api is returning eloquent models/collection, just return them as they are and see what happens =)
@Carlsson87 thank you for details explanation how it works :) I still don't know what to do though. My API won't return models on regular basis, what it returns are strings and arrays mostly. What would be perfect for me is (simple and dummy example):
class ApiController extends BaseController {
public function postGetLuckyNumber() {
return 7;
}
public function postGetDogName() {
return 'Rocky';
}
}
Which would get transformed to JSON for me. Simply: ANYTHING I'd return in API Controller would be returned as JSON with appropriate headers, just what Response::json does.
Sign in to participate in this thread!
The Laravel portal for problem solving, knowledge sharing and community building.
The community