Skip to content

Commit 9c57afc

Browse files
authored
[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
1 parent 9763eff commit 9c57afc

File tree

2 files changed

+25
-1
lines changed

2 files changed

+25
-1
lines changed

src/Illuminate/Http/Resources/Json/PaginatedResourceResponse.php

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -28,7 +28,7 @@ public function toResponse($request)
2828
$this->resource->jsonOptions()
2929
), function ($response) use ($request) {
3030
$response->original = $this->resource->resource->map(function ($item) {
31-
return is_array($item) ? Arr::get($item, 'resource') : $item->resource;
31+
return is_array($item) ? Arr::get($item, 'resource') : optional($item)->resource;
3232
});
3333

3434
$this->resource->withResponse($request, $response);

tests/Integration/Http/ResourceTest.php

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1723,6 +1723,30 @@ public function testItWontKeysIfAnyOfThemAreStrings()
17231723
], ['data' => [0 => 10, 1 => 20, 'total' => 30]]);
17241724
}
17251725

1726+
public function testItThrowsNoErrorInStrictModeWhenResourceIsPaginated()
1727+
{
1728+
$originalMode = Model::preventsAccessingMissingAttributes();
1729+
Model::preventAccessingMissingAttributes();
1730+
try {
1731+
Route::get('/', function () {
1732+
$paginator = new LengthAwarePaginator(
1733+
collect([new Post(['id' => 5, 'title' => 'Test Title', 'reading_time' => 3.0])]),
1734+
10, 15, 1
1735+
);
1736+
1737+
return PostResourceWithJsonOptions::collection($paginator);
1738+
});
1739+
1740+
$response = $this->withoutExceptionHandling()->get(
1741+
'/', ['Accept' => 'application/json']
1742+
);
1743+
1744+
$response->assertStatus(200);
1745+
} finally {
1746+
Model::preventAccessingMissingAttributes($originalMode);
1747+
}
1748+
}
1749+
17261750
private function assertJsonResourceResponse($data, $expectedJson)
17271751
{
17281752
Route::get('/', function () use ($data) {

0 commit comments

Comments
 (0)