John Davidson

cakephp - Cake PHP PatchEntities saveing the epoc


I inherited a cake application and I am having some trouble with date-times stuff.

When I save a submission I have to format the date to be Y-m-d. This allows the patchEntities() to save but when I check the data base the date is the epoc.

Current Code

$get_data = $this->request->getData();
foreach ($get_data as $key => $value) {
if(isset($get_data[$key]['lease_submissions']) && is_array($get_data[$key]['lease_submissions'])){
foreach($get_data[$key]['lease_submissions'] as $key_i => $value_i){
var_dump(date("Y-m-d", strtotime($get_data[$key]['lease_submissions'][$key_i]['reporting_period'])));
$get_data[$key]['lease_submissions'][$key_i]['reporting_period'] = date("Y-m-d", strtotime($get_data[$key]['lease_submissions'][$key_i]['reporting_period']));
$leases = $this->Leases->patchEntities($leases, $get_data);
echo "<pre>";
echo "</pre>";
$has_errors = false;
foreach ($leases as $lease) {
if (!empty($lease->errors())) {
$has_errors = true;
$this->Flash->error('Lease reading could not be saved. Please check for any errors and try again.', 'flash', ['clear' => true]);

Sample Submission

array(2) {
string(3) "805"
array(1) {
array(4) {
string(3) "805"
string(10) "2021-09-01"
string(6) "209598"
string(3) "dog"

Sample record saved

object(App\Model\Entity\LeaseSubmission)#305 (12) {
object(Cake\I18n\FrozenDate)#330 (3) {
string(26) "0169-05-08 00:00:00.000000"
string(3) "UTC"
string(3) "dog"

As you can see the reporting_period is set to the epoc. I am stumped any help is welcome.

My Answer:
Submission->patchEntity($submission, $this->request->getData());
$submission->date = date('Y-m-d', strtotime($this->request->getData('date')));

In this code, you are formatting the date before saving it using the patchEntity() method. However, the issue may be with how the date is being saved in the database. CakePHP may be converting the date to a Unix timestamp (epoch) before saving it.

To ensure that the date is saved in the correct format in the database, you can specify the data type of the date field in your entity class. For example:

// In your Submission entity class
protected $_accessible = [
'date' => true,

protected $_hidden = [

protected $_virtual = [

This will tell CakePHP to treat the date field as a string and not convert it to a Unix timestamp. This should ensure that the date is saved in the correct format in the database.

Additionally, you can also check the database configuration to make sure that the date field is set to store dates in the correct format (Y-m-d) and not as a Unix timestamp.

Rate this post

5 of 5 based on 8876 votes


© 2024 - Personal Blogs Platform. All Rights Reserved.
Create blog  |  Privacy Policy  |  Terms & Conditions  |  Contact Us