Skip to content
Prev Previous commit
Next Next commit
Add toPrettyJson to JsonResource
  • Loading branch information
WendellAdriel committed Aug 21, 2025
commit a97b70352e64e2705a777acc616bd8f9630b87a4
14 changes: 13 additions & 1 deletion src/Illuminate/Http/Resources/Json/JsonResource.php
Original file line number Diff line number Diff line change
Expand Up @@ -135,7 +135,7 @@ public function toArray(Request $request)
}

/**
* Convert the model instance to JSON.
* Convert the resource to JSON.
*
* @param int $options
* @return string
Expand All @@ -153,6 +153,18 @@ public function toJson($options = 0)
return $json;
}

/**
* Convert the resource to a pretty print formatted JSON.
*
* @return string
*
* @throws \Illuminate\Database\Eloquent\JsonEncodingException
*/
public function toPrettyJson()
{
return $this->toJson(JSON_PRETTY_PRINT);
}

/**
* Get any additional data that should be returned with the resource array.
*
Expand Down
19 changes: 19 additions & 0 deletions tests/Http/JsonResourceTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -46,4 +46,23 @@ public function testJsonResourceToJsonSucceedsWithPriorErrors(): void

$this->assertSame('{"foo":"bar"}', $resource->toJson(JSON_THROW_ON_ERROR));
}

public function testJsonResourceToPrettyPrint(): void
{
$model = new class extends Model {
};

$resource = m::mock(JsonResource::class, ['resource' => $model])
->makePartial()
->shouldReceive('jsonSerialize')->once()->andReturn(['foo' => 'bar', 'bar' => 'foo'])
->getMock();

$results = $resource->toPrettyJson();
$expected = $resource->toJson(JSON_PRETTY_PRINT);

$this->assertJsonStringEqualsJsonString($expected, $results);
$this->assertSame($expected, $results);
$this->assertStringContainsString("\n", $results);
$this->assertStringContainsString(' ', $results);
}
}