skip to Main Content

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


  1. Chosen as BEST ANSWER

    Accidentally I discovered that when I return array

    return ['result' => 4 ];
    

    then response have Content-Type: application/json and not have debugbar stuff - I have no idea why - but it works :)


  2. 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:

    use Response; // IlluminateSupportFacadesResponse (or Laravel 4.2 equivalent)
    
    class ExampleController extends Controller {
      public function exampleRequest(){
        return Response::json(['result' => 4], 200);
      }
    }
    

    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

    return Response::json(4);`
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search