Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[5.4] Make date/datetime cast difference more explicit by removing time part. #16799

Merged
merged 1 commit into from
Dec 14, 2016
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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