From dbbeafbeb9e88d5f4d7dd3c154897300cc71aa30 Mon Sep 17 00:00:00 2001 From: Lupacescu Eduard Date: Tue, 22 Dec 2020 12:22:14 +0200 Subject: [PATCH] Fixing belongs to nullable. (#327) * Fixing belongs to nullable. * Apply fixes from StyleCI (#328) --- src/Fields/EagerField.php | 6 ++++++ tests/Fields/BelongsToFieldTest.php | 17 +++++++++++++++++ 2 files changed, 23 insertions(+) diff --git a/src/Fields/EagerField.php b/src/Fields/EagerField.php index ed37281c..f95efe2e 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 44bb7588..a61bb010 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) {