diff --git a/src/Fields/EagerField.php b/src/Fields/EagerField.php index ed37281c8..f95efe2ef 100644 --- a/src/Fields/EagerField.php +++ b/src/Fields/EagerField.php @@ -52,6 +52,12 @@ public function resolve($repository, $attribute = null) $relatedModel = $model->{$this->relation}()->first(); + if (is_null($relatedModel)) { + $this->value = null; + + return $this; + } + try { $this->value = $this->repositoryClass::resolveWith($relatedModel) ->allowToShow(app(Request::class)) diff --git a/tests/Fields/BelongsToFieldTest.php b/tests/Fields/BelongsToFieldTest.php index 44bb7588a..a61bb010f 100644 --- a/tests/Fields/BelongsToFieldTest.php +++ b/tests/Fields/BelongsToFieldTest.php @@ -78,6 +78,23 @@ public function test_unauthorized_see_relationship() }); } + public function test_dont_show_key_when_nullable_related() + { + $_SERVER['restify.users.show'] = true; + + Gate::policy(User::class, UserPolicy::class); + + tap(factory(Post::class)->create([ + 'user_id' => null, + ]), function ($post) { + $this->get(PostWithUserRepository::uriKey()."/{$post->id}?related=user") + ->assertJsonFragment([ + 'user' => null, + ]) + ->assertOk(); + }); + } + public function test_field_used_when_storing() { tap(factory(User::class)->create(), function ($user) {