From c803c68cca7a33094273c30119eec8c074f52f93 Mon Sep 17 00:00:00 2001 From: Bram Date: Mon, 5 Jan 2026 14:04:18 +0100 Subject: [PATCH] Handle null resource more gracefully in toId --- src/Traits/Id.php | 4 ++++ tests/Unit/JsonApiResourceTest.php | 8 ++++++++ 2 files changed, 12 insertions(+) diff --git a/src/Traits/Id.php b/src/Traits/Id.php index 0b826f0..b422d0d 100644 --- a/src/Traits/Id.php +++ b/src/Traits/Id.php @@ -6,6 +6,10 @@ trait Id { private function getId(): int|string|null { + if ($this->resource === null) { + return null; + } + return $this->toId() ?? $this->guessId(); } diff --git a/tests/Unit/JsonApiResourceTest.php b/tests/Unit/JsonApiResourceTest.php index cfddd21..d859507 100644 --- a/tests/Unit/JsonApiResourceTest.php +++ b/tests/Unit/JsonApiResourceTest.php @@ -35,6 +35,14 @@ public function test_non_eloquent_resource() $response->assertJsonFragment(['id' => $intern->id]); } + public function test_null_resource_handled_gracefully() + { + Route::get('test-route', fn () => new InternResource(null)); + $response = $this->getJson('test-route'); + + $response->assertJson(['data' => []]); + } + public function test_basic_resource_collection() { $developers = Developer::factory()->count(3)->create();