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

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

merged 1 commit into from
Dec 14, 2016

Conversation

jarnovanleeuwen
Copy link
Contributor

@jarnovanleeuwen jarnovanleeuwen commented Dec 14, 2016

Hi,

Currently, both date and datetime cast types are using the same casting method. However, this can lead to unexpected results when a UNIX timestamp or Carbon instance containing a time part is assigned to a date attribute. date attributes keep the time part when it is known, but after saving the model and refreshing it, the time part might be lost. Example:

use Carbon\Carbon;
use Illuminate\Database\Eloquent\Model;
class User extends Model
{
    protected $casts = [
        'date_of_birth' => 'date'
    ];
}

$dob = Carbon::now(); // 2016-12-14 15:18:34
$today = Carbon::today(); // 2016-12-14 00:00:00

$user = new User;
$user->date_of_birth = $dob;
$user->save();

if ($dob->eq($today)) {
    print "Born today";
} else {
    print "Not born today";
}

$user = $user->fresh();

if ($dob->eq($today)) {
    print "Born today";
} else {
    print "Not born today";
}

// Actual output:
// Not born today
// Born today

// Expected output:
// Born today
// Born today

As the cast types explicitly include both date and datetime, I think a more consistent approach would be to always remove the time part from date attributes.

Kind regards,
Jarno

@taylorotwell taylorotwell merged commit 5a3d722 into laravel:master Dec 14, 2016
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants