Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

timestampTz fields in Laravel

Laravel 5.4 supports the Postgres TIMESTAMP WITH TIME ZONE field type in migrations:

$table->timestampTz('scheduled_for');

Laravel can be set up to convert date fields (DATE, DATETIME, TIMESTAMP) into Carbon objects (and does so by default for the created_at and updated_at TIMESTAMP fields), but putting scheduled_for into the $dates field causes an error with the timezone-aware version:

InvalidArgumentException with message 'Trailing data'

Looking in the database and tinker, the field's value appears to be something like 2017-06-19 19:19:19-04. Is there a native way to get a Carbon object out of one of these field types? Or am I stuck using an accessor?

like image 492
ceejayoz Avatar asked Jun 19 '17 20:06

ceejayoz


1 Answers

Resurrecting this question, hopefully with a helpful answer that gets accepted.

Laravel assumes a Y-m-d H:i:s database timestamp format. If you're using a Postgres timestampz column, that's obviously different. You need to tell Eloquent how to get Carbon to parse that format.

Simply define the $dateFormat property on your model like so:

Class MyModel extends Eloquent {

    protected $dateFormat = 'Y-m-d H:i:sO';

}

Credit where credit is due: I found this solution in a GitHub issue

like image 56
Jim Rubenstein Avatar answered Nov 04 '22 20:11

Jim Rubenstein