Friday 29 May 2020

Lumen - insert datetime

At one stage, I couldn't insert a record into table with datetime format.
I know MySQL supports DateTime and TimeStamp for date formats. I tried both of them, error still was same.




Error message was below.

Invalid datetime format: 1292 Incorrect datetime value: '2020-05-29T12:09:52.000Z' for column 'dt_date_received'.

I knew that it was API error. js gave current time as 'new Date()'. And API received it as string. And it had timezone information from the js date (you cannot remove this timezone information because js date is just integer value basically in some way).

Imagine you run SQL command below. You will get exactly the same error as above.



I couldn't figure out, so I tried API Test, which I made for simple CRUD test. It didn't work here either. In below, the first two 'ggg' was inserted into store, but not database. So it didn't show id.



Then I googled how to edit $request data in Laravel. And I found below link!
https://stackoverflow.com/questions/36812476/how-to-change-value-of-a-request-parameter-in-laravel



You can edit the $request data before inserting into database.


The data was inserted as expected!
Further, I replaced the given dt_date_received with replacing 'T' and 'Z'.




It was working.

Actually all this errors happened because I had to include 'dt_date_received' into 'fillable' to update/create record with that column information.



You need this to create record with some timestamp value.


Imagine you omit the line 25 in the above picture. Then it becomes you try below SQL query.


And in this case, because 'dt_date_received' is 'not null' column, you will have another error.
'dt_date'_received' cannot be null.


In Summary,

  1. If insert is not working, go for API Test for simple testing
  2. Read error message
  3. Try API code change to resolve the issue.


No comments:

Post a Comment