Skip to content

Commit

Permalink
Properly cast to date by removing time part. (#16799)
Browse files Browse the repository at this point in the history
  • Loading branch information
jarnovanleeuwen authored and taylorotwell committed Dec 14, 2016
1 parent ed02967 commit 5a3d722
Show file tree
Hide file tree
Showing 2 changed files with 24 additions and 0 deletions.
12 changes: 12 additions & 0 deletions src/Illuminate/Database/Eloquent/Model.php
Original file line number Diff line number Diff line change
Expand Up @@ -2920,6 +2920,7 @@ protected function castAttribute($key, $value)
case 'collection':
return new BaseCollection($this->fromJson($value));
case 'date':
return $this->asDate($value);
case 'datetime':
return $this->asDateTime($value);
case 'timestamp':
Expand Down Expand Up @@ -3028,6 +3029,17 @@ public function fromDateTime($value)
return $value->format($format);
}

/**
* Return a timestamp as DateTime object with time set to 00:00:00.
*
* @param mixed $value
* @return \Carbon\Carbon
*/
protected function asDate($value)
{
return $this->asDateTime($value)->startOfDay();
}

/**
* Return a timestamp as DateTime object.
*
Expand Down
12 changes: 12 additions & 0 deletions tests/Database/DatabaseEloquentModelTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -1409,6 +1409,18 @@ public function testModelAttributesAreCastedWhenPresentInCastsArray()
$this->assertEquals(-14173440, $arr['timestampAttribute']);
}

public function testModelDateAttributeCastingResetsTime()
{
$model = new EloquentModelCastingStub;
$model->setDateFormat('Y-m-d H:i:s');
$model->dateAttribute = '1969-07-20 22:56:00';

$this->assertEquals('1969-07-20 00:00:00', $model->dateAttribute->toDateTimeString());

$arr = $model->toArray();
$this->assertEquals('1969-07-20 00:00:00', $arr['dateAttribute']);
}

public function testModelAttributeCastingPreservesNull()
{
$model = new EloquentModelCastingStub;
Expand Down

0 comments on commit 5a3d722

Please sign in to comment.