Laravel created_at field updates with current date

Asked by: joseph-brandt
Date:
Viewed: 2271
Answers: 1
  • 0

Hi,

In my Laravel site I have a CRUD functionality. I noticed that whenever I update my post, the created_at field is also updated. 

I exported my table and I noticed this:

`created_at` timestamp NOT NULL DEFAULT current_timestamp() ON UPDATE current_timestamp(),
`updated_at` timestamp NULL DEFAULT NULL

Does this mean that whenever I update the review post the created_at date is also updated? How do I prevent this?

Answers

Answer by: ChristianKovats

Answered on: 19 Nov 2023 Marked as best by question author

  • 2

The ON UPDATE part that is applied is not typical for a created_at column.

It means that every time the row is updated, the created_at field will also be updated to the current timestamp. This is not standard behavior for a created_at column, as usually, you would want this field to remain constant once the record is created, indicating when the record was initially created.

If your created_at column is set to update on every change to the record, it will not serve its intended purpose of tracking when the record was originally created. Instead, it will always show when the record was last updated, which is typically the role of the updated_at column.

If you want the created_at column to function as intended (storing the creation date/time of the record and not changing after that), you should remove the ON UPDATE current_timestamp() part from its definition. The SQL to change this would look something like:

ALTER TABLE posts MODIFY COLUMN created_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP;

This command will modify the created_at column to keep its default value as the current timestamp but will not update it on every row update. This change will align with the standard behavior expected in Laravel and most database designs for tracking record creation and update times.

Please log in to post an answer!