Skip to content

Commit 932bb69

Browse files
committed
Fix ID conversion for toJson and toArray
1 parent 3f30502 commit 932bb69

File tree

2 files changed

+11
-6
lines changed

2 files changed

+11
-6
lines changed

src/Jenssegers/Mongodb/Model.php

Lines changed: 10 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -195,14 +195,18 @@ public function attributesToArray()
195195
{
196196
$attributes = parent::attributesToArray();
197197

198+
// Because the original Eloquent never returns objects, we convert
199+
// MongoDB related objects to a string representation. This kind
200+
// of mimics the SQL behaviour so that dates are formatted
201+
// nicely when your models are converted to JSON.
198202
foreach ($attributes as &$value)
199203
{
200-
/**
201-
* Here we convert MongoDate instances to string. This mimics
202-
* original SQL behaviour so that dates are formatted nicely
203-
* when your models are converted to JSON.
204-
*/
205-
if ($value instanceof MongoDate)
204+
if ($value instanceof MongoId)
205+
{
206+
$value = (string) $value;
207+
}
208+
209+
else if ($value instanceof MongoDate)
206210
{
207211
$value = $this->asDateTime($value)->format($this->getDateFormat());
208212
}

tests/ModelTest.php

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -287,6 +287,7 @@ public function testToArray()
287287
$this->assertEquals(array('_id', 'created_at', 'name', 'type', 'updated_at'), $keys);
288288
$this->assertTrue(is_string($array['created_at']));
289289
$this->assertTrue(is_string($array['updated_at']));
290+
$this->assertTrue(is_string($array['_id']));
290291
}
291292

292293
public function testUnset()

0 commit comments

Comments
 (0)