CakePHP set CreatedAt field on save

So after a quick search I found that CakePHP automatically updates ‘created’ and ‘modified’ for you. Well the database I already had setup uses the fields ‘CreatedAt’ and ‘UpdatedAt’ instead. I didn’t want to go through and modify almost every table in the database just so I don’t have to set the CreatedAt date manually with every new record.

So to make sure I get CreatedAt set on new records I added this to my AppModel.php

public function beforeSave($options = array()) {
        parent::beforeSave($options);
        if(!isset($this->data[$this->alias]['id'])) {
                $this->data[$this->alias]['CreatedAt'] = date("Y/m/d H:i:s");
        }
}

Before the data is actually saved and if there is no id, since new records wouldn’t have one yet, it sets ‘CreatedAt’ to the current time. If there is a way to change ‘created’ to ‘CreatedAt’ I would prefer to do that, but this is working for me at the moment.

Because ‘UpdatedAt’ is set to update to the current timestamp on update through the database, I don’t have to worry about CakePHP doing it for me.

Go back to top