Laravel 5 how to handle created_at automatically but not update_at
Eloquent handles timestamps in updateTimestamps()
:
protected function updateTimestamps()
{
$time = $this->freshTimestamp();
if ( ! $this->isDirty(static::UPDATED_AT))
{
$this->setUpdatedAt($time);
}
if ( ! $this->exists && ! $this->isDirty(static::CREATED_AT))
{
$this->setCreatedAt($time);
}
}
You can simply override this function in your model and remove the part updatedAt
:
protected function updateTimestamps()
{
$time = $this->freshTimestamp();
if ( ! $this->exists && ! $this->isDirty(static::CREATED_AT))
{
$this->setCreatedAt($time);
}
}
Or you can just override setUpdatedAt
, although you might want to keep this intentionally for setting the value:
public function setUpdatedAt($value)
{
// do nothing
}
source to share
One way to achieve the above is to change the model events. Add the following method to your model.
public static function boot()
{
public $timestamps = false;
parent::boot();
static::creating(function($model) {
$dateTime = new DateTime;
$model->created_at = $dateTime->format('m-d-y H:i:s');
return true;
});
static::updating(function($model) {
$dateTime = new DateTime;
$model->updated_at = $dateTime->format('m-d-y H:i:s');
return true;
});
}
You can now access the model creation and update events. Within these events, you can do whatever you want, in your case, you can change the timestamps. For more information on model events see the Laravel documentation Model Events
source to share
All or nothing for functionality outside the box.
By replicating the for-only functionality created_at
, you can use eloquent events. For each of your models, you can do the following
class MyModel extends Eloquent
{
protected $timestamps = false;
public static function boot()
{
parent::boot();
static::creating(function($model)
{
$model->created_at = Carbon::now();
});
}
}
Every time a new model is created, this sets the column created_at
to the current time using Carbon.
source to share