Skip to content

Commit

Permalink
allow closure
Browse files Browse the repository at this point in the history
  • Loading branch information
taylorotwell committed Nov 11, 2016
1 parent f3cdef0 commit 9b59f67
Showing 1 changed file with 12 additions and 6 deletions.
18 changes: 12 additions & 6 deletions src/Illuminate/Database/Eloquent/Relations/HasOne.php
Original file line number Diff line number Diff line change
Expand Up @@ -2,26 +2,30 @@

namespace Illuminate\Database\Eloquent\Relations;

use Closure;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Collection;

class HasOne extends HasOneOrMany
{
/**
* Determine whether getResults should return a default new model instance or not.
* Indicates if a default model instance should be used.
*
* @var bool
* Alternatively, may be a Closure to execute to retrieve default value.
*
* @var \Closure|bool
*/
protected $withDefault = false;
protected $withDefault;

/**
* Return a new model instance in case the relationship does not exist.
*
* @param \Closure|bool $callback
* @return $this
*/
public function withDefault()
public function withDefault($callback = true)
{
$this->withDefault = true;
$this->withDefault = $callback;

return $this;
}
Expand Down Expand Up @@ -73,7 +77,9 @@ public function match(array $models, Collection $results, $relation)
*/
protected function getDefaultFor(Model $model)
{
if ($this->withDefault) {
if (is_callable($this->withDefault)) {
return call_user_func($this->withDefault);
} elseif ($this->withDefault === true) {
return $this->related->newInstance()->setAttribute(
$this->getPlainForeignKey(), $model->getAttribute($this->localKey)
);
Expand Down

0 comments on commit 9b59f67

Please sign in to comment.