SupportsDefaultModels.php 1.5KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  1. <?php
  2. namespace Illuminate\Database\Eloquent\Relations\Concerns;
  3. use Illuminate\Database\Eloquent\Model;
  4. trait SupportsDefaultModels
  5. {
  6. /**
  7. * Indicates if a default model instance should be used.
  8. *
  9. * Alternatively, may be a Closure or array.
  10. *
  11. * @var \Closure|array|bool
  12. */
  13. protected $withDefault;
  14. /**
  15. * Make a new related instance for the given model.
  16. *
  17. * @param \Illuminate\Database\Eloquent\Model $parent
  18. * @return \Illuminate\Database\Eloquent\Model
  19. */
  20. abstract protected function newRelatedInstanceFor(Model $parent);
  21. /**
  22. * Return a new model instance in case the relationship does not exist.
  23. *
  24. * @param \Closure|array|bool $callback
  25. * @return $this
  26. */
  27. public function withDefault($callback = true)
  28. {
  29. $this->withDefault = $callback;
  30. return $this;
  31. }
  32. /**
  33. * Get the default value for this relation.
  34. *
  35. * @param \Illuminate\Database\Eloquent\Model $parent
  36. * @return \Illuminate\Database\Eloquent\Model|null
  37. */
  38. protected function getDefaultFor(Model $parent)
  39. {
  40. if (! $this->withDefault) {
  41. return;
  42. }
  43. $instance = $this->newRelatedInstanceFor($parent);
  44. if (is_callable($this->withDefault)) {
  45. return call_user_func($this->withDefault, $instance, $parent) ?: $instance;
  46. }
  47. if (is_array($this->withDefault)) {
  48. $instance->forceFill($this->withDefault);
  49. }
  50. return $instance;
  51. }
  52. }