Skip to content

Commit

Permalink
Allow Eloquent has one relations to return a default new model
Browse files Browse the repository at this point in the history
  • Loading branch information
sileence committed Oct 31, 2016
1 parent 47480d7 commit a948c08
Showing 1 changed file with 24 additions and 1 deletion.
25 changes: 24 additions & 1 deletion src/Illuminate/Database/Eloquent/Relations/HasOne.php
Original file line number Diff line number Diff line change
Expand Up @@ -6,14 +6,37 @@

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.
*
* @return mixed
*/
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()
);
}
}

/**
Expand Down

0 comments on commit a948c08

Please sign in to comment.