diff --git a/src/Illuminate/Http/Resources/Json/JsonResource.php b/src/Illuminate/Http/Resources/Json/JsonResource.php index 832607a9dabd..1228c9babe38 100644 --- a/src/Illuminate/Http/Resources/Json/JsonResource.php +++ b/src/Illuminate/Http/Resources/Json/JsonResource.php @@ -75,7 +75,11 @@ public static function make(...$parameters) */ public static function collection($resource) { - return new AnonymousResourceCollection($resource, static::class); + return tap(new AnonymousResourceCollection($resource, static::class), function ($collection) { + if (property_exists(static::class, 'preserveKeys')) { + $collection->preserveKeys = (new static([]))->preserveKeys === true; + } + }); } /** diff --git a/tests/Integration/Http/ResourceTest.php b/tests/Integration/Http/ResourceTest.php index 01a845e8f1a8..0f4ebdc791a1 100644 --- a/tests/Integration/Http/ResourceTest.php +++ b/tests/Integration/Http/ResourceTest.php @@ -3,6 +3,7 @@ namespace Illuminate\Tests\Integration\Http; use Orchestra\Testbench\TestCase; +use Illuminate\Support\Collection; use Illuminate\Support\Facades\Route; use Illuminate\Http\Resources\MergeValue; use Illuminate\Http\Resources\MissingValue; @@ -629,6 +630,39 @@ public function test_keys_are_preserved_if_the_resource_is_flagged_to_preserve_k $response->assertJson(['data' => $data]); } + public function test_keys_are_preserved_in_an_anonymous_colletion_if_the_resource_is_flagged_to_preserve_keys() + { + $data = Collection::make([ + [ + 'id' => 1, + 'authorId' => 5, + 'bookId' => 22, + ], + [ + 'id' => 2, + 'authorId' => 5, + 'bookId' => 15, + ], + [ + 'id' => 3, + 'authorId' => 42, + 'bookId' => 12, + ], + ])->keyBy->id; + + Route::get('/', function () use ($data) { + return ResourceWithPreservedKeys::collection($data); + }); + + $response = $this->withoutExceptionHandling()->get( + '/', ['Accept' => 'application/json'] + ); + + $response->assertStatus(200); + + $response->assertJson(['data' => $data->toArray()]); + } + public function test_leading_merge_keyed_value_is_merged_correctly() { $filter = new class {