Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to handle unset/default dates in Laravel? (with Carbon)

Laravel automatically passes the created_at and the updated_at (from an Eloquent model) into a new Carbon instance, as per the documentation.

It seems though, that if the value is the default 0000-00-00 00:00:00 it outputs the following: -0001-11-30 06:12:32 for all 0000-00-00 00:00:00 values.

The fields are set to timestamp type.

I'm using the following at the moment (within the model), but it feels clumsy to have to do this across all Laravel models that may contain a default/unset date.

public function getCreatedAtAttribute($value) {
    return $value == "0000-00-00 00:00:00" ? "0000-00-00 00:00:00" : $value;
}
like image 992
Chris Avatar asked Oct 04 '13 06:10

Chris


2 Answers

This is happening in the getAttributeValue method, in model.php

elseif (in_array($key, $this->getDates()))
    {
        if ($value) return $this->asDateTime($value);
    }

as it is being passed to the asDateTime method. This could be fixed with something like

elseif (in_array($key, $this->getDates()))
    {
        if ($value && $value !== '0000-00-00 00:00:00') return $this->asDateTime($value);
    }

Could this be an issue for a pull request?

like image 124
alou Avatar answered Oct 18 '22 00:10

alou


There seems to be no clean way to do this. So I went with:

public function getCreatedAtAttribute($value) {
    return $value == "0000-00-00 00:00:00" ? "0000-00-00 00:00:00" : $value;
}
like image 45
Chris Avatar answered Oct 17 '22 23:10

Chris