Reputation: 1497
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.
Upvotes: 6
Views: 17604
Reputation: 706
In Laravel 5.2 you can use a similar approach using the helpers
return response()->json($data=[], $status=200, $headers=[], $options=JSON_PRETTY_PRINT)
Upvotes: 1
Reputation: 191
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
Upvotes: 18
Reputation: 2166
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");
Upvotes: 5
Reputation: 76646
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);
Upvotes: 7
Reputation: 126
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.
Upvotes: 1