Skip to content

Commit dbbeafb

Browse files
authored
Fixing belongs to nullable. (#327)
* Fixing belongs to nullable. * Apply fixes from StyleCI (#328)
1 parent d474838 commit dbbeafb

File tree

2 files changed

+23
-0
lines changed

2 files changed

+23
-0
lines changed

src/Fields/EagerField.php

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -52,6 +52,12 @@ public function resolve($repository, $attribute = null)
5252

5353
$relatedModel = $model->{$this->relation}()->first();
5454

55+
if (is_null($relatedModel)) {
56+
$this->value = null;
57+
58+
return $this;
59+
}
60+
5561
try {
5662
$this->value = $this->repositoryClass::resolveWith($relatedModel)
5763
->allowToShow(app(Request::class))

tests/Fields/BelongsToFieldTest.php

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -78,6 +78,23 @@ public function test_unauthorized_see_relationship()
7878
});
7979
}
8080

81+
public function test_dont_show_key_when_nullable_related()
82+
{
83+
$_SERVER['restify.users.show'] = true;
84+
85+
Gate::policy(User::class, UserPolicy::class);
86+
87+
tap(factory(Post::class)->create([
88+
'user_id' => null,
89+
]), function ($post) {
90+
$this->get(PostWithUserRepository::uriKey()."/{$post->id}?related=user")
91+
->assertJsonFragment([
92+
'user' => null,
93+
])
94+
->assertOk();
95+
});
96+
}
97+
8198
public function test_field_used_when_storing()
8299
{
83100
tap(factory(User::class)->create(), function ($user) {

0 commit comments

Comments
 (0)