framework: Blueprint::timestamps not setup correctly. Update_at doing nothing and created_at doing updated_at

So basically after you run a migration to create a table with Blueprint::timestamps() method, such as the create_users migration that comes with Laravel, the columns are setup incorrectly. Almost backwards.

Problem

  1. So upon table creation both columns are set to 0000-00.00 00:00:00
  2. Then, upon an insert the created_at column sets the current time. Everything is fine so far…
  3. Upon update of the same row however, the created_at column updates again to the current time and the updated_at column never changes from 0000-00-00 00:00:00.

Possible Solution

The correct column attributes for those columns to achieve the desired behavior is:

created_at TIMESTAMP DEFAULT 0
updated_at TIMESTAMP ON UPDATE CURRENT_TIMESTAMP

Essentially, DEFAULT 0 is telling created_at to be NOT NULL. Therefore, when an INSERT INTO query passes NULL to it, it gets the current time and won’t update again. However, it looks like you have to pass NULL to the created_at column upon the initial INSERT INTO or it will remain 0000-00-00 00:00:00.

Unfortunatety you can’t have CURRENT_TIMESTAMP or NOW() or any combination of those on two TIMESTAMP columns so this is the common work around.

Hope that helps.

About this issue

  • Original URL
  • State: closed
  • Created 8 years ago
  • Comments: 20 (8 by maintainers)

Most upvoted comments

I don’t understand your question. The columns shouldn’t auto-initialize at the database level. That is handled by Eloquent.