Home » Php » php – CakePHP: auto-set model create and update dates

php – CakePHP: auto-set model create and update dates

Posted by: admin July 12, 2020 Leave a comment


Is there a way to configure CakePHP models to automatically set timestamps, such as created_on and updated_on, when saving the object?

I’m thinking of an equivalent to Django’s DateTimeField’s auto_now and auto_now_add options.

I’ve heard this is a controversial practice in some frameworks, but I want to do it anyway.

If you can’t do this, do people normally set the timestamps in the beforeSave() handlers, perhaps by checking if the model data already contains an id field and setting a creation data accordingly?

Thanks, and apologies if I’ve missed the relevant bit in the docs.

How to&Answers:

Yes, CakePHP does this automagically for the fields created and modified.

In MySQL, the type for these fields should be DATETIME (or DATE) and NULLable.


If you name your fields created and modified and make them of type datetime, Cake will handle the rest. http://book.cakephp.org/complete/1000/Models#created-and-modified-1015


Actually, use “now()” for updating datetime in mysql is simple and easy.

$updateField = array('last_login'=>'now()');