From 9c57afc014a3518a915d75630c8883155bc44d38 Mon Sep 17 00:00:00 2001 From: Bruno <39590058+Katalam@users.noreply.github.com> Date: Tue, 30 Jul 2024 08:57:53 +0200 Subject: [PATCH] [11.X] "Model::preventAccessingMissingAttributes()" Causes Exception During Pagination with ResourceCollection (#52305) * fix: add optional item resource access to paginated resource response * test: add a paginated collection response test when model is in strict mode --- .../Json/PaginatedResourceResponse.php | 2 +- tests/Integration/Http/ResourceTest.php | 24 +++++++++++++++++++ 2 files changed, 25 insertions(+), 1 deletion(-) diff --git a/src/Illuminate/Http/Resources/Json/PaginatedResourceResponse.php b/src/Illuminate/Http/Resources/Json/PaginatedResourceResponse.php index a6190c51a9ac..d15d27396bae 100644 --- a/src/Illuminate/Http/Resources/Json/PaginatedResourceResponse.php +++ b/src/Illuminate/Http/Resources/Json/PaginatedResourceResponse.php @@ -28,7 +28,7 @@ public function toResponse($request) $this->resource->jsonOptions() ), function ($response) use ($request) { $response->original = $this->resource->resource->map(function ($item) { - return is_array($item) ? Arr::get($item, 'resource') : $item->resource; + return is_array($item) ? Arr::get($item, 'resource') : optional($item)->resource; }); $this->resource->withResponse($request, $response); diff --git a/tests/Integration/Http/ResourceTest.php b/tests/Integration/Http/ResourceTest.php index 56cee847887c..579d086f3986 100644 --- a/tests/Integration/Http/ResourceTest.php +++ b/tests/Integration/Http/ResourceTest.php @@ -1723,6 +1723,30 @@ public function testItWontKeysIfAnyOfThemAreStrings() ], ['data' => [0 => 10, 1 => 20, 'total' => 30]]); } + public function testItThrowsNoErrorInStrictModeWhenResourceIsPaginated() + { + $originalMode = Model::preventsAccessingMissingAttributes(); + Model::preventAccessingMissingAttributes(); + try { + Route::get('/', function () { + $paginator = new LengthAwarePaginator( + collect([new Post(['id' => 5, 'title' => 'Test Title', 'reading_time' => 3.0])]), + 10, 15, 1 + ); + + return PostResourceWithJsonOptions::collection($paginator); + }); + + $response = $this->withoutExceptionHandling()->get( + '/', ['Accept' => 'application/json'] + ); + + $response->assertStatus(200); + } finally { + Model::preventAccessingMissingAttributes($originalMode); + } + } + private function assertJsonResourceResponse($data, $expectedJson) { Route::get('/', function () use ($data) {