Gireesh Gireesh - 7 months ago 253
PHP Question

Wrong DateTime in created_at and updated_at fields in Laravel 5.2

I am using jenssegers mongodb
I am trying to save created_at and updated_at in my controller,

"updated_at" : ISODate("1970-01-11T19:45:21.925Z"),
"created_at" : ISODate("1970-01-11T19:45:21.925Z")


and even for update also, the wrong dates are saving

in my app.php

in aliases

'Moloquent' => 'Jenssegers\Mongodb\Eloquent\Model',


in providers

'Jenssegers\Mongodb\Auth\PasswordResetServiceProvider',


in my model

use Moloquent;

class Task extends Moloquent{
//$fillables = [];
}


enter image description here

Please help me in solving the issue
Thanks in advance!

Answer

Actually - when using jenssegers/Laravel-MongoDB package - created_at and updated_at attributes are automatically set when saving a new model object.

However if you still want manually set timestamps or anything else datetime field you MUST convert a DateTime object (or Carbon) to MongoDB\BSON\UTCDateTime.

So it would be something like this:

$myModel = new MyModel();
$myModel->created_at = $myModel->fromDateTime(new \DateTime());
//...

And for another datetime attribute other than created_at/updated_at:

class Task extends Model
{
    protected  $collection = 'tasks';

    protected $duedate;

    protected  $dates = ['duedate'];

    /** Mutator */
    public function setDuedateAttribute($value)
    {
        /** @var \MongoDB\BSON\UTCDateTime */
        $this->attributes['duedate'] = $this->fromDateTime(
            \DateTime::createFromFormat('d/m/Y H:i', $value . '00:00'));
    }
}

Jenssegers\Mongodb\Eloquent::fromDateTime() is available from any model instance as it inherits from parent model (see in github). This method convert a DateTime to a storable UTCDateTime object (which is the internal datetime mongo rep).