jeudi 12 juillet 2018

Postgres + laravel timestamps with timezones

I have a parent class as below that extends Illuminate\Database\Eloquent\Model and would, in turn, extend it to my models in Laravel 5.6. I have date columns to store timestamps with timezones using $table->timestampsTz(); $table->softDeletesTz(); I can get the records through tinker, however when I view them in a browser, where I guess date serialization goes totally wrong and I end up with this error:

InvalidArgumentException
Unexpected data found.

 InvalidArgumentException
…/vendor/nesbot/carbon/src/Carbon/Carbon.php 775 

What am I missing?

class BaseModel extends EloquentModel {

    use SoftDeletes;

    protected $primaryKey = 'id';

    public $incrementing = false;

    protected $keyType = 'string';

    protected $dates = [
        'created_at',
        'updated_at',
        'deleted_at'
    ];

    protected $dateFormat = 'Y-m-d H:i:s.u';

    public function getDateFormat() {
        return 'Y-m-d H:i:s.u';
    }

    private function mutateTimestampValue($timestamp) {
        return \Carbon\Carbon::parse($timestamp)->timezone( config('app.timezone') )->format('c');
    }

    public function getCreatedAtAttribute($value) {

        return $this->mutateTimestampValue($value);
    }

    public function getUpdatedAtAttribute($value) {

        return $this->mutateTimestampValue($value);
    }

    public function getDeletedAtAttribute($value) {

        return $this->mutateTimestampValue($value);
    }

    protected static function boot() {
        parent::boot();
        self::creating(function ($model) {
            $model->{$model->getKeyName()} = (string) Str::orderedUuid();
        });
    }
}



via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire