1<?php 2 3namespace Illuminate\Database\Eloquent\Concerns; 4 5use Illuminate\Support\Facades\Date; 6 7trait HasTimestamps 8{ 9 /** 10 * Indicates if the model should be timestamped. 11 * 12 * @var bool 13 */ 14 public $timestamps = true; 15 16 /** 17 * Update the model's update timestamp. 18 * 19 * @return bool 20 */ 21 public function touch() 22 { 23 if (! $this->usesTimestamps()) { 24 return false; 25 } 26 27 $this->updateTimestamps(); 28 29 return $this->save(); 30 } 31 32 /** 33 * Update the creation and update timestamps. 34 * 35 * @return void 36 */ 37 public function updateTimestamps() 38 { 39 $time = $this->freshTimestamp(); 40 41 $updatedAtColumn = $this->getUpdatedAtColumn(); 42 43 if (! is_null($updatedAtColumn) && ! $this->isDirty($updatedAtColumn)) { 44 $this->setUpdatedAt($time); 45 } 46 47 $createdAtColumn = $this->getCreatedAtColumn(); 48 49 if (! $this->exists && ! is_null($createdAtColumn) && ! $this->isDirty($createdAtColumn)) { 50 $this->setCreatedAt($time); 51 } 52 } 53 54 /** 55 * Set the value of the "created at" attribute. 56 * 57 * @param mixed $value 58 * @return $this 59 */ 60 public function setCreatedAt($value) 61 { 62 $this->{$this->getCreatedAtColumn()} = $value; 63 64 return $this; 65 } 66 67 /** 68 * Set the value of the "updated at" attribute. 69 * 70 * @param mixed $value 71 * @return $this 72 */ 73 public function setUpdatedAt($value) 74 { 75 $this->{$this->getUpdatedAtColumn()} = $value; 76 77 return $this; 78 } 79 80 /** 81 * Get a fresh timestamp for the model. 82 * 83 * @return \Illuminate\Support\Carbon 84 */ 85 public function freshTimestamp() 86 { 87 return Date::now(); 88 } 89 90 /** 91 * Get a fresh timestamp for the model. 92 * 93 * @return string 94 */ 95 public function freshTimestampString() 96 { 97 return $this->fromDateTime($this->freshTimestamp()); 98 } 99 100 /** 101 * Determine if the model uses timestamps. 102 * 103 * @return bool 104 */ 105 public function usesTimestamps() 106 { 107 return $this->timestamps; 108 } 109 110 /** 111 * Get the name of the "created at" column. 112 * 113 * @return string|null 114 */ 115 public function getCreatedAtColumn() 116 { 117 return static::CREATED_AT; 118 } 119 120 /** 121 * Get the name of the "updated at" column. 122 * 123 * @return string|null 124 */ 125 public function getUpdatedAtColumn() 126 { 127 return static::UPDATED_AT; 128 } 129 130 /** 131 * Get the fully qualified "created at" column. 132 * 133 * @return string|null 134 */ 135 public function getQualifiedCreatedAtColumn() 136 { 137 return $this->qualifyColumn($this->getCreatedAtColumn()); 138 } 139 140 /** 141 * Get the fully qualified "updated at" column. 142 * 143 * @return string|null 144 */ 145 public function getQualifiedUpdatedAtColumn() 146 { 147 return $this->qualifyColumn($this->getUpdatedAtColumn()); 148 } 149} 150