I work on old system – laravel 4.1/4.2 – my controler returns number in response:
return 4;
but browser shows Content-Type: text/html
(not json) and debugbar add also some html to that response.
When I try this from laravel doc:
return Response::json(['result' => 4 ]);
I get error (I to of php controler file I have use SymfonyComponentHttpFoundationResponse;
)
Call to undefined method SymfonyComponentHttpFoundationResponse::json()
I also try to use
$response = new Response(200, array(), ['result' => 4]);
return $response->json();
but I get
The HTTP status code "0" is not valid.
How to get json in response (without debugbar stuff)?
Update: (I test proposition from Tim Levis comment)
When I try (with and without use Response
)
return response()->json(['result' => 4], 200);
I get
Call to undefined function AppControllersApiresponse()
Update2: Someone suggest that there is already answer for Laravel 5 – which actually works in L4 – but this is accidentally I think – usually L5 solutions NOT works on L4 so we should not mix this two framework versions
2
Answers
Accidentally I discovered that when I return array
then response have
Content-Type: application/json
and not have debugbar stuff - I have no idea why - but it works :)Response::json()
should work in Laravel 4.2, as versions prior to 5 used Facades (Response::
) instead of global methods (response()
).The main issue here is the imported
Response
class is not the Facade, but rather a Symphony component. To fix this issue, use the correct import:Sidenote;
return ['result' => 4];
"works", as Laravel guesses content type for return statements in Controllers, but it’s better to be specific to avoid any issues.Update: you can use shortcut which works without
use Response
statement