I want to add created_at and updated_at columns in a custom table and update both columns on saving the data.

1 Answer 1


Follow below steps to update the created_at and update_at columns on saving the data in the table.

  1. Create created_at and update_at columns in the database table.

................. <column xsi:type="timestamp" name="created_at" on_update="false" nullable="false" default="CURRENT_TIMESTAMP" comment="Creation Time"/> <column xsi:type="timestamp" name="updated_at" on_update="true" nullable="false" default="CURRENT_TIMESTAMP" comment="Update Time"/> .................

  1. Update the Model/CustomTable.php file to add beforeSave() function.
use Magento\Framework\Api\DataObjectHelper;
class CustomTable extends \Magento\Framework\Model\AbstractModel
     * @var \Magento\Framework\Stdlib\DateTime
    private $dateTime;

    public function __construct(
        \Magento\Framework\Model\Context $context,
        \Magento\Framework\Registry $registry,
        \Magento\Framework\Stdlib\DateTime $dateTime,
        DataObjectHelper $dataObjectHelper,
        array $data = []
    ) {
        $this->dateTime = $dateTime;
        $this->dataObjectHelper = $dataObjectHelper;

     * Prepare data to be saved to database.
     * @return $this
    public function beforeSave()
        if ($this->isObjectNew() && !$this->getCreatedAt()) {

        return $this;

Hope this works for you.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.