From abafa55868bdcb72b3983c9ce09ec8bb25b9793d Mon Sep 17 00:00:00 2001 From: Connor Tumbleson Date: Thu, 26 Nov 2020 09:30:32 -0500 Subject: [PATCH] [8.x] Fix issue with polymorphic morphMaps with literal 0 (#35364) * fix: use strict null check on morphTo type * test: assert 0 relation_type is handled correctly --- .../Database/Eloquent/Concerns/HasRelationships.php | 2 +- tests/Database/DatabaseEloquentMorphToTest.php | 10 ++++++++++ 2 files changed, 11 insertions(+), 1 deletion(-) diff --git a/src/Illuminate/Database/Eloquent/Concerns/HasRelationships.php b/src/Illuminate/Database/Eloquent/Concerns/HasRelationships.php index 92c3758e15f9..e2fce30492fa 100644 --- a/src/Illuminate/Database/Eloquent/Concerns/HasRelationships.php +++ b/src/Illuminate/Database/Eloquent/Concerns/HasRelationships.php @@ -233,7 +233,7 @@ public function morphTo($name = null, $type = null, $id = null, $ownerKey = null // If the type value is null it is probably safe to assume we're eager loading // the relationship. In this case we'll just pass in a dummy query where we // need to remove any eager loads that may already be defined on a model. - return empty($class = $this->{$type}) + return is_null($class = $this->{$type}) ? $this->morphEagerTo($name, $type, $id, $ownerKey) : $this->morphInstanceTo($class, $name, $type, $id, $ownerKey); } diff --git a/tests/Database/DatabaseEloquentMorphToTest.php b/tests/Database/DatabaseEloquentMorphToTest.php index 5f9049b4a4a5..0365c2af6c32 100644 --- a/tests/Database/DatabaseEloquentMorphToTest.php +++ b/tests/Database/DatabaseEloquentMorphToTest.php @@ -90,6 +90,16 @@ public function testMorphToWithArrayDefault() $this->assertSame('taylor', $result->username); } + public function testMorphToWithZeroMorphType() + { + $parent = $this->getMockBuilder(EloquentMorphToModelStub::class)->onlyMethods(['getAttribute', 'morphEagerTo', 'morphInstanceTo'])->getMock(); + $parent->method('getAttribute')->with('relation_type')->willReturn(0); + $parent->expects($this->once())->method('morphInstanceTo'); + $parent->expects($this->never())->method('morphEagerTo'); + + $parent->relation(); + } + public function testMorphToWithSpecifiedClassDefault() { $parent = new EloquentMorphToModelStub;