HasTimestamps.php 2.4KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127
  1. <?php
  2. namespace Illuminate\Database\Eloquent\Concerns;
  3. use Illuminate\Support\Carbon;
  4. trait HasTimestamps
  5. {
  6. /**
  7. * Indicates if the model should be timestamped.
  8. *
  9. * @var bool
  10. */
  11. public $timestamps = true;
  12. /**
  13. * Update the model's update timestamp.
  14. *
  15. * @return bool
  16. */
  17. public function touch()
  18. {
  19. if (! $this->usesTimestamps()) {
  20. return false;
  21. }
  22. $this->updateTimestamps();
  23. return $this->save();
  24. }
  25. /**
  26. * Update the creation and update timestamps.
  27. *
  28. * @return void
  29. */
  30. protected function updateTimestamps()
  31. {
  32. $time = $this->freshTimestamp();
  33. if (! is_null(static::UPDATED_AT) && ! $this->isDirty(static::UPDATED_AT)) {
  34. $this->setUpdatedAt($time);
  35. }
  36. if (! $this->exists && ! is_null(static::CREATED_AT) &&
  37. ! $this->isDirty(static::CREATED_AT)) {
  38. $this->setCreatedAt($time);
  39. }
  40. }
  41. /**
  42. * Set the value of the "created at" attribute.
  43. *
  44. * @param mixed $value
  45. * @return $this
  46. */
  47. public function setCreatedAt($value)
  48. {
  49. $this->{static::CREATED_AT} = $value;
  50. return $this;
  51. }
  52. /**
  53. * Set the value of the "updated at" attribute.
  54. *
  55. * @param mixed $value
  56. * @return $this
  57. */
  58. public function setUpdatedAt($value)
  59. {
  60. $this->{static::UPDATED_AT} = $value;
  61. return $this;
  62. }
  63. /**
  64. * Get a fresh timestamp for the model.
  65. *
  66. * @return \Illuminate\Support\Carbon
  67. */
  68. public function freshTimestamp()
  69. {
  70. return new Carbon;
  71. }
  72. /**
  73. * Get a fresh timestamp for the model.
  74. *
  75. * @return string
  76. */
  77. public function freshTimestampString()
  78. {
  79. return $this->fromDateTime($this->freshTimestamp());
  80. }
  81. /**
  82. * Determine if the model uses timestamps.
  83. *
  84. * @return bool
  85. */
  86. public function usesTimestamps()
  87. {
  88. return $this->timestamps;
  89. }
  90. /**
  91. * Get the name of the "created at" column.
  92. *
  93. * @return string
  94. */
  95. public function getCreatedAtColumn()
  96. {
  97. return static::CREATED_AT;
  98. }
  99. /**
  100. * Get the name of the "updated at" column.
  101. *
  102. * @return string
  103. */
  104. public function getUpdatedAtColumn()
  105. {
  106. return static::UPDATED_AT;
  107. }
  108. }