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

Skip to content

Commit 1fc228b

Browse files
committed
Merge branch '4.1' into 4.2
2 parents f7fe364 + 8da08c2 commit 1fc228b

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
@@ -2152,6 +2152,16 @@ public function attributesToArray()
21522152
{
21532153
$attributes = $this->getArrayableAttributes();
21542154

2155+
// If an attribute is a date, we will cast it to a string after converting it
2156+
// to a DateTime / Carbon instance. This is so we will get some consistent
2157+
// formatting while accessing attributes vs. arraying / JSONing a model.
2158+
foreach ($this->getDates() as $key)
2159+
{
2160+
if ( ! array_key_exists($key, $attributes)) continue;
2161+
2162+
$attributes[$key] = (string) $this->asDateTime($attributes[$key]);
2163+
}
2164+
21552165
// We want to spin through all the mutated attributes for this model and call
21562166
// the mutator for the attribute. We cache off every mutated attributes so
21572167
// 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

@@ -470,6 +471,38 @@ public function testToArray()
470471
}
471472

472473

474+
public function testToArrayIncludesDefaultFormattedTimestamps()
475+
{
476+
$model = new EloquentDateModelStub;
477+
$model->setRawAttributes(array(
478+
'created_at' => '2012-12-04',
479+
'updated_at' => '2012-12-05',
480+
));
481+
482+
$array = $model->toArray();
483+
484+
$this->assertEquals('2012-12-04 00:00:00', $array['created_at']);
485+
$this->assertEquals('2012-12-05 00:00:00', $array['updated_at']);
486+
}
487+
488+
489+
public function testToArrayIncludesCustomFormattedTimestamps()
490+
{
491+
Carbon\Carbon::setToStringFormat('d-m-y');
492+
493+
$model = new EloquentDateModelStub;
494+
$model->setRawAttributes(array(
495+
'created_at' => '2012-12-04',
496+
'updated_at' => '2012-12-05',
497+
));
498+
499+
$array = $model->toArray();
500+
501+
$this->assertEquals('04-12-12', $array['created_at']);
502+
$this->assertEquals('05-12-12', $array['updated_at']);
503+
}
504+
505+
473506
public function testVisibleCreatesArrayWhitelist()
474507
{
475508
$model = new EloquentModelStub;

0 commit comments

Comments
 (0)