diff --git a/src/Illuminate/Database/Eloquent/Relations/MorphTo.php b/src/Illuminate/Database/Eloquent/Relations/MorphTo.php index 95acb81c1bac..b47340188417 100644 --- a/src/Illuminate/Database/Eloquent/Relations/MorphTo.php +++ b/src/Illuminate/Database/Eloquent/Relations/MorphTo.php @@ -223,6 +223,21 @@ public function dissociate() return $this->parent->setRelation($this->relation, null); } + /** + * Touch all of the related models for the relationship. + * + * @return void + */ + public function touch() + { + // If there is no related model, we'll just return to prevent an invalid query. + if (is_null($this->ownerKey)) { + return; + } + + parent::touch(); + } + /** * Remove all or passed registered global scopes. * diff --git a/tests/Integration/Database/EloquentMorphToTouchesTest.php b/tests/Integration/Database/EloquentMorphToTouchesTest.php new file mode 100644 index 000000000000..470ff2e05a79 --- /dev/null +++ b/tests/Integration/Database/EloquentMorphToTouchesTest.php @@ -0,0 +1,67 @@ +increments('id'); + $table->timestamps(); + }); + + Schema::create('comments', function (Blueprint $table) { + $table->increments('id'); + $table->nullableMorphs('commentable'); + }); + + Post::create(); + } + + public function test_not_null() + { + $comment = (new Comment)->commentable()->associate(Post::first()); + + \DB::enableQueryLog(); + + $comment->save(); + + $this->assertCount(2, \DB::getQueryLog()); + } + + public function test_null() + { + \DB::enableQueryLog(); + + Comment::create(); + + $this->assertCount(1, \DB::getQueryLog()); + } +} + +class Comment extends Model +{ + public $timestamps = false; + + protected $touches = ['commentable']; + + public function commentable() + { + return $this->morphTo(); + } +} + +class Post extends Model +{ +}