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.

1

5 Answers 5

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

Sign up to request clarification or add additional context in comments.

Comments

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

2 Comments

Why first making a response and then decode and encode again? The variant by @XoneFobic is better.
@Reflic: Definitely needs moar coffee. Updated the post, thanks :)
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");

Comments

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.

Comments

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)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.