Pretty Print JSON Response in Laravel 9

Pretty Print JSON Response in Laravel 9

In Laravel application, we can return an HTTP response in JSON format. During development can be useful to return formatted JSON that can be much easier to read when debugging an application.

This tutorial provides example how to pretty print JSON response in Laravel 9 application.

A constructor of the JsonResponse class accepts options argument which can be used to specify JSON encoding options. We can create a new class that specifies JSON_PRETTY_PRINT option by default.

app/Http/Responses/PrettyJsonResponse.php

<?php

namespace App\Http\Responses;

use Illuminate\Http\JsonResponse;

class PrettyJsonResponse extends JsonResponse
{
    public function __construct(
        mixed $data = null,
        int $status = 200,
        array $headers = [],
        int $options = 0,
        bool $json = false
    ) {
        $options |= JSON_PRETTY_PRINT;
        parent::__construct($data, $status, $headers, $options, $json);
    }
}

A new class can be used in controller as follows:

app/Http/Controllers/TestController.php

<?php

namespace App\Http\Controllers;

use App\Http\Responses\PrettyJsonResponse;
use Illuminate\Http\JsonResponse;

class TestController extends Controller
{
    public function index(): JsonResponse
    {
        return new PrettyJsonResponse(
            [
                'name' => 'John',
                'age' => 25,
            ]
        );
    }
}

Leave a Comment

Cancel reply

Your email address will not be published.