6
return Response::json(array(
    'status' => 200,
    'posts' => $post->toArray()
), 200);

Using the code above I returned data in json format.
I have seen other api's that return json giving it back in formatted view.
Like:

http://api.steampowered.com/ISteamNews/GetNewsForApp/v0002/?appid=440&count=3&maxlength=300&format=json

But mine is returning it in one line. How do I generate the json in a formatted way with laravel?


update

I cannot test the code yet until I tomorrow. So I'll accept the answer tom.

But this is the api

http://laravel.com/api/class-Illuminate.Support.Facades.Response.html

and the parameters are,

$data
$status
$headers

update

Actually I modified the response class of illuminate to have that constant.

madziikoy
  • 1,447
  • 7
  • 22
  • 32
  • 1
    you have solutions here: http://stackoverflow.com/questions/6054033/pretty-printing-json-with-php – Amir Bar Dec 19 '13 at 10:18

5 Answers5

18

It is possible in current 4.2 version.

Response::json($data=[], $status=200, $headers=[], $options=JSON_PRETTY_PRINT);

https://github.com/laravel/framework/commit/417f539803ce96eeab7b420d8b03f04959a603e9

Travis Miller
  • 191
  • 1
  • 5
7

I don't think Laravel allows you to format the JSON output. However, you can do it using json_encode()'s JSON_PRETTY_PRINT constant (available since PHP 5.4.0). Here's how:

$array = array(
    'status' => 200,
    'posts' => $post->toArray()
);

return json_encode($array, JSON_PRETTY_PRINT);
Amal Murali
  • 75,622
  • 18
  • 128
  • 150
5

The same answer but with the json content-type (like the example in the question):

return Response::make(json_encode(array(
    'status' => 200,
    'posts' => $post->toArray()
), JSON_PRETTY_PRINT))->header('Content-Type', "application/json");
1

This is (to my knowledge) a server-side setting. Like xDebug will format it like that (also colours it).

By default, JSON is a single string. And isn't related to Laravel or any other framework.

If you're using PHP 5.4+ You could use JSON_PRETTY_PRINT

return json_encode(array(
    'status' => 200,
    'posts' => $post->toArray()
), JSON_PRETTY_PRINT);

Untested and you could look in Laravel api if it's possible to use Response::json() for it.

XoneFobic
  • 126
  • 1
1

In Laravel 5.2 you can use a similar approach using the helpers

return response()->json($data=[], $status=200, $headers=[], $options=JSON_PRETTY_PRINT)
Giovanne Afonso
  • 666
  • 7
  • 21