Skip to content

Commit 9b59f67

Browse files
committed
allow closure
1 parent f3cdef0 commit 9b59f67

1 file changed

Lines changed: 12 additions & 6 deletions

File tree

  • src/Illuminate/Database/Eloquent/Relations

src/Illuminate/Database/Eloquent/Relations/HasOne.php

Lines changed: 12 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -2,26 +2,30 @@
22

33
namespace Illuminate\Database\Eloquent\Relations;
44

5+
use Closure;
56
use Illuminate\Database\Eloquent\Model;
67
use Illuminate\Database\Eloquent\Collection;
78

89
class HasOne extends HasOneOrMany
910
{
1011
/**
11-
* Determine whether getResults should return a default new model instance or not.
12+
* Indicates if a default model instance should be used.
1213
*
13-
* @var bool
14+
* Alternatively, may be a Closure to execute to retrieve default value.
15+
*
16+
* @var \Closure|bool
1417
*/
15-
protected $withDefault = false;
18+
protected $withDefault;
1619

1720
/**
1821
* Return a new model instance in case the relationship does not exist.
1922
*
23+
* @param \Closure|bool $callback
2024
* @return $this
2125
*/
22-
public function withDefault()
26+
public function withDefault($callback = true)
2327
{
24-
$this->withDefault = true;
28+
$this->withDefault = $callback;
2529

2630
return $this;
2731
}
@@ -73,7 +77,9 @@ public function match(array $models, Collection $results, $relation)
7377
*/
7478
protected function getDefaultFor(Model $model)
7579
{
76-
if ($this->withDefault) {
80+
if (is_callable($this->withDefault)) {
81+
return call_user_func($this->withDefault);
82+
} elseif ($this->withDefault === true) {
7783
return $this->related->newInstance()->setAttribute(
7884
$this->getPlainForeignKey(), $model->getAttribute($this->localKey)
7985
);

0 commit comments

Comments
 (0)