HasTimestamps.php 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125
  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 && ! $this->isDirty(static::CREATED_AT)) {
  37. $this->setCreatedAt($time);
  38. }
  39. }
  40. /**
  41. * Set the value of the "created at" attribute.
  42. *
  43. * @param mixed $value
  44. * @return $this
  45. */
  46. public function setCreatedAt($value)
  47. {
  48. $this->{static::CREATED_AT} = $value;
  49. return $this;
  50. }
  51. /**
  52. * Set the value of the "updated at" attribute.
  53. *
  54. * @param mixed $value
  55. * @return $this
  56. */
  57. public function setUpdatedAt($value)
  58. {
  59. $this->{static::UPDATED_AT} = $value;
  60. return $this;
  61. }
  62. /**
  63. * Get a fresh timestamp for the model.
  64. *
  65. * @return \Illuminate\Support\Carbon
  66. */
  67. public function freshTimestamp()
  68. {
  69. return new Carbon;
  70. }
  71. /**
  72. * Get a fresh timestamp for the model.
  73. *
  74. * @return string
  75. */
  76. public function freshTimestampString()
  77. {
  78. return $this->fromDateTime($this->freshTimestamp());
  79. }
  80. /**
  81. * Determine if the model uses timestamps.
  82. *
  83. * @return bool
  84. */
  85. public function usesTimestamps()
  86. {
  87. return $this->timestamps;
  88. }
  89. /**
  90. * Get the name of the "created at" column.
  91. *
  92. * @return string
  93. */
  94. public function getCreatedAtColumn()
  95. {
  96. return static::CREATED_AT;
  97. }
  98. /**
  99. * Get the name of the "updated at" column.
  100. *
  101. * @return string
  102. */
  103. public function getUpdatedAtColumn()
  104. {
  105. return static::UPDATED_AT;
  106. }
  107. }