-
Notifications
You must be signed in to change notification settings - Fork 11.1k
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
1 parent
1137d86
commit ed0182b
Showing
1 changed file
with
63 additions
and
0 deletions.
There are no files selected for viewing
63 changes: 63 additions & 0 deletions
63
src/Illuminate/Database/Eloquent/Relations/Concerns/SupportsDefaultModels.php
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,63 @@ | ||
<?php | ||
|
||
namespace Illuminate\Database\Eloquent\Relations\Concerns; | ||
|
||
use Illuminate\Database\Eloquent\Model; | ||
|
||
trait SupportsDefaultModels | ||
{ | ||
/** | ||
* Indicates if a default model instance should be used. | ||
* | ||
* Alternatively, may be a Closure or array. | ||
* | ||
* @var \Closure|array|bool | ||
*/ | ||
protected $withDefault; | ||
|
||
/** | ||
* Make a new related instance for the given model. | ||
* | ||
* @param \Illuminate\Database\Eloquent\Model $parent | ||
* @return \Illuminate\Database\Eloquent\Model | ||
*/ | ||
abstract protected function newRelatedInstanceFor(Model $parent); | ||
|
||
/** | ||
* Return a new model instance in case the relationship does not exist. | ||
* | ||
* @param \Closure|array|bool $callback | ||
* @return $this | ||
*/ | ||
public function withDefault($callback = true) | ||
{ | ||
$this->withDefault = $callback; | ||
|
||
return $this; | ||
} | ||
|
||
/** | ||
* Get the default value for this relation. | ||
* | ||
* @param \Illuminate\Database\Eloquent\Model $parent | ||
* @return \Illuminate\Database\Eloquent\Model|null | ||
*/ | ||
protected function getDefaultFor(Model $parent) | ||
{ | ||
if (! $this->withDefault) { | ||
return; | ||
} | ||
|
||
$instance = $this->newRelatedInstanceFor($parent); | ||
|
||
if (is_callable($this->withDefault)) { | ||
return call_user_func($this->withDefault, $instance) ?: $instance; | ||
} | ||
|
||
if (is_array($this->withDefault)) { | ||
$instance->forceFill($this->withDefault); | ||
} | ||
|
||
return $instance; | ||
} | ||
} |