Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Commit 6080903

Browse files
committed
Merge branch 'f/eloquentToArrayCarbonDates' of https://github.com/danharper/framework into danharper-f/eloquentToArrayCarbonDates
2 parents 4399562 + 36a41cb commit 6080903

2 files changed

Lines changed: 43 additions & 0 deletions

File tree

src/Illuminate/Database/Eloquent/Model.php

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2200,6 +2200,16 @@ public function attributesToArray()
22002200
{
22012201
$attributes = $this->getArrayableAttributes();
22022202

2203+
// Convert all attributes listed as dates to DateTime instances, then back
2204+
// to a string. This allows us to output date attributes in the same format
2205+
// as if we were to access them directly on the object.
2206+
foreach ($this->getDates() as $key)
2207+
{
2208+
if ( ! array_key_exists($key, $attributes)) continue;
2209+
2210+
$attributes[$key] = (string) $this->asDateTime($attributes[$key]);
2211+
}
2212+
22032213
// We want to spin through all the mutated attributes for this model and call
22042214
// the mutator for the attribute. We cache off every mutated attributes so
22052215
// we don't have to constantly check on attributes that actually change.

tests/Database/DatabaseEloquentModelTest.php

Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,7 @@ public function tearDown()
99
m::close();
1010

1111
Illuminate\Database\Eloquent\Model::unsetEventDispatcher();
12+
Carbon\Carbon::resetToStringFormat();
1213
}
1314

1415

@@ -496,6 +497,38 @@ public function testToArray()
496497
}
497498

498499

500+
public function testToArrayIncludesDefaultFormattedTimestamps()
501+
{
502+
$model = new EloquentDateModelStub;
503+
$model->setRawAttributes(array(
504+
'created_at' => '2012-12-04',
505+
'updated_at' => '2012-12-05',
506+
));
507+
508+
$array = $model->toArray();
509+
510+
$this->assertEquals('2012-12-04 00:00:00', $array['created_at']);
511+
$this->assertEquals('2012-12-05 00:00:00', $array['updated_at']);
512+
}
513+
514+
515+
public function testToArrayIncludesCustomFormattedTimestamps()
516+
{
517+
Carbon\Carbon::setToStringFormat('d-m-y');
518+
519+
$model = new EloquentDateModelStub;
520+
$model->setRawAttributes(array(
521+
'created_at' => '2012-12-04',
522+
'updated_at' => '2012-12-05',
523+
));
524+
525+
$array = $model->toArray();
526+
527+
$this->assertEquals('04-12-12', $array['created_at']);
528+
$this->assertEquals('05-12-12', $array['updated_at']);
529+
}
530+
531+
499532
public function testVisibleCreatesArrayWhitelist()
500533
{
501534
$model = new EloquentModelStub;

0 commit comments

Comments
 (0)