Eloquent update method change created_at timestamp

- 1 answer


I'm using Eloquent for database handling, when I update a record with update method created_at time stamp is changed how to prevent this from happening ?

$post = Post::update([
   'name' => $name

updated_at timestamp is working perfectly




In case you don't have any custom settings in your model. You can update record like this:

$id = 5; // here put id of record you want to update
$post = Post::findOrFail($id);
$post->name = $name;

Using this code only name should be updated and updated_at timestamp (and not created_at). If created_at is also updated it means you might have some custom model settings or:

  • you might have database triggers that change created_at when record is updated
  • you might have registered some events that change created_at when record is updated
  • make sure your created_at field in posts table in database is not defined as CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP - this way whenever you update record, created_at will be also updated to current datetime

You should also make sure that you don't have for your Post model something like this:

const UPDATED_AT = 'created_at';

If would also explain why created_at is changed when you update your record.

source: stackoverflow.com