Laravel-mongodb: Store Carbon DateTime ISO object in Sub Json Document in Laravel 5.2 MongoDB

Created on 22 Jul 2016  路  12Comments  路  Source: jenssegers/laravel-mongodb

I am trying to store Carbon datetime in Sub Json Document but instead of storing in ISO format its storing in different way shown below.

"_id" : ObjectId("5791bc3d6e79d211aa5be019"),
"breakUps" : [ 
   {
        "amount" : 2000,
        "expiry" : {
            "date" : "2016-09-05 06:25:01.000000",
            "timezone_type" : 3,
            "timezone" : "UTC"
        }
    }
],
"updated_at" : ISODate("2016-07-22T06:25:01.576Z"),
"created_at" : ISODate("2016-07-22T06:25:01.576Z")

Instead it should have been stored like ISODate("2016-07-22T06:25:01.576Z") format.

My Eloquent Model class is:

class Configurations extends Eloquent
{
    public $incrementing = false;
    public  $timestamps = true;
    protected $collection = 'configurations';
    protected $dates = array('created_at','updated_at','breakUps.expiry');
}

Most helpful comment

$created_at = Carbon::now()->toDateTimeString();
$date = new \MongoDB\BSON\UTCDateTime(new \DateTime($created_at));

Now you can insert $date to mongo

All 12 comments

Same problem with we

You could solve that by creating an embedded model breakUps with
protected $dates = [ 'expiry' ];

Same problem here. Its seems that in nested array its doesnt work, just in main level

protected $dates = [ 'expiry' ];

neither something like this
protected $dates = [ 'breakUps.expiry' ];

Maybe a custom function that emulate "$dates" when you create/fill the record.

@zuljin
I solved it by using UTCDateTime instead of Carbon dates.

It works in subdocuments as well. Like this:

'expiry' => new UTCDateTime(strtotime("now") * 1000)

$model->breakUps['expiry'] = $model->freshTimestamp() worked for me, which used UTCDateTime internally like @ricardo mentioned.

Is this still unfixed?

Is this still unfixed?

it seems still unfixed.

Why @jenssegers closed this post?
Is there anybody who knows how to fix it?

$created_at = Carbon::now()->toDateTimeString();
$date = new \MongoDB\BSON\UTCDateTime(new \DateTime($created_at));

Now you can insert $date to mongo

It's quite insane using this method.

Same issue here, with Laravel 7 and latest development HEAD. Why is this issue closed, is there a solution?

Was this page helpful?
0 / 5 - 0 ratings

Related issues

HassanIbrahim picture HassanIbrahim  路  3Comments

bastiendonjon picture bastiendonjon  路  3Comments

lgt picture lgt  路  3Comments

yupangestu picture yupangestu  路  3Comments

pirmax picture pirmax  路  3Comments