diff --git a/src/Illuminate/Database/Eloquent/Relations/HasOne.php b/src/Illuminate/Database/Eloquent/Relations/HasOne.php index 52ad2a612c13..7aade0a63f56 100755 --- a/src/Illuminate/Database/Eloquent/Relations/HasOne.php +++ b/src/Illuminate/Database/Eloquent/Relations/HasOne.php @@ -6,6 +6,20 @@ class HasOne extends HasOneOrMany { + protected $withDefault = false; + + /** + * Return a new model instance in case the relationship does not exist. + * + * @return $this + */ + public function withDefault() + { + $this->withDefault = true; + + return $this; + } + /** * Get the results of the relationship. * @@ -13,7 +27,16 @@ class HasOne extends HasOneOrMany */ public function getResults() { - return $this->query->first(); + if ($result = $this->query->first()) { + return $result; + } + + if ($this->withDefault) { + return $this->related->newInstance() + ->setAttribute( + $this->getPlainForeignKey(), $this->getParentKey() + ); + } } /**