Suppose we have a 2015-02-05T14:50:55+01:00
formatted date time that comes from an angularJs client side app.
Now I want to save it as DATETIME
MySQL in a table.
I know that is a iso 8601
formatted date time. because of this I added below code to my model:
protected $dateFormat = 'DATE_ISO8601';
But when I want to update my model with this new field I got this error :
A textual day could not be found
Meridian can only come after an hour has been found
The format separator does not match
The format separator does not match
The format separator does not match
The timezone could not be found in the database
Data missing {"userId":1,"email":"ahmadbadpey@gmail.com","exception":"[object] (InvalidArgumentException(code: 0): A textual day could not be found
Meridian can only come after an hour has been found
The format separator does not match
The format separator does not match
The format separator does not match
The timezone could not be found in the database
Data missing at D:\\wamp\\www\\zarsystem\\vendor\
esbot\\carbon\\src\\Carbon\\Carbon.php:582)
[stacktrace]
#0 D:\\wamp\\www\\zarsystem\\vendor\\laravel\\framework\\src\\Illuminate\\Database\\Eloquent\\Concerns\\HasAttributes.php(715): Carbon\\Carbon::createFromFormat('DATE_ISO8601', '2015-02-05T14:5...')
I tried some other Predefined Constants like DATE_ATOM
,DATE_W3C
, ... but got same erorrs.
I confused and I do not know what should I do ?
You can do this instead:
protected $dateFormat = 'c';
c
is ISO 8601 date.
http://php.net/manual/en/function.date.php
Also, I believe that's not what you want since you've said previously you want to keep dates in a standard format in the DB which is Y-m-d H:i:s
.
So, you should add an accessor to transform date after you're getting it from DB and a mutator to transform from ISO 8601
back to Y-m-d H:i:s
before saving it to DB.
By default, timestamps are formatted as 'Y-m-d H:i:s'. If you need to customize the timestamp format, set the $dateFormat property on your model. This property determines how date attributes are stored in the database, as well as their format when the model is serialized to an array or JSON
https://laravel.com/docs/5.5/eloquent-mutators#date-mutators
DATE_ISO8601
is a constant, defined in the DateTime
class you're trying to use a format mask string of 'DATE_ISO8601'
You should be able to do
protected $dateFormat = \DateTime::DATE_ISO8601;
However, this format is not compatible with ISO-8601, but is left this way for backward compatibility reasons; so it is better to use the ATOM constant
protected $dateFormat = \DateTime::ATOM;