Failed to parse time no eloquent

Asked

Viewed 72 times

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?

  • 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.

  • Because the created_at is treated as a date by the created just no, but only as string

  • 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

1 answer

2

This error seems to have nothing to do with the query, but the moment Laravel tries to instantiate the eloquent, it transforms the fields created_at and updated_at into a Carbon/Datetime type by default. You can take this functionality from Laravel using public $timestamps = false; in the template, but ai should manage created_at and updated_at manually when creating/updating the record.

The solution I suggest is customize the serialization of this field, without doing in the query, using:

protected $casts = [
    'created_at' => 'datetime:d/m/Y'
];
  • 1

    worked out, thank you so much for the tip!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.