0
I have the following code:
select('id','title', 'description', 'author', DB::raw("DATE_FORMAT(created_at,'%d/%m/%Y') AS created_at"))->get();
when I run it returns me the following error:
erro": "Could not parse '19/06/2021': DateTime::__construct(): Failed to parse time string (19/06/2021) at position 0 (1): Unexpected character
worth resaltar the tests I did and realized that:
1 - changing the alias (AS) to another name as created it formats normally, but need the name to be actually created_at;
2 - Works on mysql even using the alias created_at
3 - if instead of formatting I use %d-%m-%Y it tbm works
the version of the Laravel q I am using is v.8.
OBS: I know you can reach someone and talk to format in php or view, but if it is an api, for this reason it should already be formatted with the name 'created_at'
The question is the format of the date used. When reading the PHP documentation, you will see that when you use the bar as a date separator, the format that will be expected is month/day/year. As there is no month 19 gives error. When you return with hyphen, it works, because the expected format becomes day-month-year. In short, switch to hyphenate, or put the month before the day in the date formatting. But... why you need the
date_format
in SQL?– Woss
the value coming from the bank is '2021-06-19 03:58:02', use date_format to leave formatted as '19/06/2021'. But the question is, why when I change my alias to created it works? if it were really the php error it would return even if I changed my alias.
– Schielke
Because the
created_at
is treated as a date by thecreated
just no, but only as string– Woss
Be careful when using DATE_FORMAT in your queries. Imagine applying DATE_FORMAT to 1 million records. Your query will be very slow. I recommend reading https://laravel.com/docs/8.x/eloquent-mutators#date-casting and https://laravel.com/docs/8.x/eloquent-mutators#Defining-an-accessor
– Marcos Xavier