I want only use created_at , how to do it?
I know:
This can custom timestamps name
const CREATED_AT = \'created\';
const UPDATED_AT = \'updat
Approach with only setUpdatedAt
did not work with Laravel 5.1.7 because it has one more place where updated_at
gets processed.
Model class performUpdate method calls Builder class method:
public function update(array $values)
{
return $this->query->update($this->addUpdatedAtColumn($values));
}
which leads us to
return Arr::add($values, $column, $this->model->freshTimestampString());
I'm not sure, why Laravel is processing updated_at twice - in performUpdate
with $this->updateTimestamps()
and then later in Builder with $this->addUpdatedAtColumn($values)
.
With some debugging, I found that you have to also update your model with getUpdatedAtColumn override. At first I was afraid that it will try to update a non-existent field "null", but it turned out that Arr::add
is smart enough to ignore null keys.
So, in your model class add these:
public function setUpdatedAt($value)
{
// Do nothing.
}
public function getUpdatedAtColumn()
{
return null;
}
This should be enough to disable both updates.
Use on the top the class:
const UPDATED_AT = null;
or
const CREATED_AT = null;
On your model
set
const UPDATED_AT = null;
or
const CREATED_AT = null;
it stops Laravel trying to update the updated_at/created_at field
It works for Laravel 5.8
And it is better than overwrite: setUpdatedAt
in your model
public function setUpdatedAt($value) : self
{
// Do nothing.
return $this;
}
because it is shorter and because the check for if (! is_null(static::UPDATED_AT)
is happening in source code earlier than triggering
setUpdatedAt
You can use CURRENT_TIMESTAMP default value for created
field in your MySQL table and set
public $timestamps = false;
in your model.
I used very simple hack ;)
class MyClass extends Model {
const CREATED_AT = 'creation_date';
const UPDATED_AT = 'creation_date';
}
I just pointed both to the same column :)
In version 5.3 I just did public $timestamps = false;
and then added protected $fillable = ['created_at']. Note: You can add anything you want, just make sure it matches the one in your table.`