Support the ongoing development of Laravel.io →
Requests IOC Architecture
Last updated 1 year ago.
0

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 =)

Last updated 1 year ago.
0

@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.

Last updated 1 year ago.
0

Does anyone know how to do it?

Last updated 1 year ago.
0

Sign in to participate in this thread!

Eventy

Your banner here too?

kokokurak kokokurak Joined 21 Aug 2014

Moderators

We'd like to thank these amazing companies for supporting us

Your logo here?

Laravel.io

The Laravel portal for problem solving, knowledge sharing and community building.

© 2024 Laravel.io - All rights reserved.