diff --git a/src/Illuminate/Database/Eloquent/Relations/MorphTo.php b/src/Illuminate/Database/Eloquent/Relations/MorphTo.php index 2739786d5e7e..d0465d590927 100644 --- a/src/Illuminate/Database/Eloquent/Relations/MorphTo.php +++ b/src/Illuminate/Database/Eloquent/Relations/MorphTo.php @@ -194,9 +194,9 @@ protected function matchToMorphParents($type, Collection $results) */ public function associate($model) { - $this->parent->setAttribute($this->foreignKey, $model->getKey()); + $this->parent->setAttribute($this->foreignKey, $model instanceof Model ? $model->getKey() : null); - $this->parent->setAttribute($this->morphType, $model->getMorphClass()); + $this->parent->setAttribute($this->morphType, $model instanceof Model ? $model->getMorphClass() : null); return $this->parent->setRelation($this->relation, $model); } diff --git a/tests/Database/DatabaseEloquentMorphToTest.php b/tests/Database/DatabaseEloquentMorphToTest.php index ac9df28d7d97..9cfdb2283a30 100644 --- a/tests/Database/DatabaseEloquentMorphToTest.php +++ b/tests/Database/DatabaseEloquentMorphToTest.php @@ -57,6 +57,20 @@ public function testAssociateMethodSetsForeignKeyAndTypeOnModel() $relation->associate($associate); } + public function testAssociateMethodIgnoresNullValue() + { + $parent = m::mock('Illuminate\Database\Eloquent\Model'); + $parent->shouldReceive('getAttribute')->once()->with('foreign_key')->andReturn('foreign.value'); + + $relation = $this->getRelationAssociate($parent); + + $parent->shouldReceive('setAttribute')->once()->with('foreign_key', null); + $parent->shouldReceive('setAttribute')->once()->with('morph_type', null); + $parent->shouldReceive('setRelation')->once()->with('relation', null); + + $relation->associate(null); + } + public function testDissociateMethodDeletesUnsetsKeyAndTypeOnModel() { $parent = m::mock('Illuminate\Database\Eloquent\Model');