Skip to content

Commit

Permalink
[11.X] "Model::preventAccessingMissingAttributes()" Causes Exception …
Browse files Browse the repository at this point in the history
…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
  • Loading branch information
Katalam authored Jul 30, 2024
1 parent 9763eff commit 9c57afc
Show file tree
Hide file tree
Showing 2 changed files with 25 additions and 1 deletion.
Original file line number Diff line number Diff line change
Expand Up @@ -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);
Expand Down
24 changes: 24 additions & 0 deletions tests/Integration/Http/ResourceTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -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) {
Expand Down

0 comments on commit 9c57afc

Please sign in to comment.