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

[10.x] Fix issues with updated_at #48230

Merged
merged 2 commits into from Aug 29, 2023
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.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
2 changes: 1 addition & 1 deletion src/Illuminate/Database/Eloquent/Builder.php
Expand Up @@ -1166,7 +1166,7 @@ protected function addUpdatedAtColumn(array $values)
) {
$timestamp = $this->model->newInstance()
->forceFill([$column => $timestamp])
->getAttributes()[$column];
->getAttributes()[$column] ?? $timestamp;
}

$values = array_merge([$column => $timestamp], $values);
Expand Down
44 changes: 44 additions & 0 deletions tests/Integration/Database/MySql/EloquentCastTest.php
Expand Up @@ -20,6 +20,13 @@ protected function defineDatabaseMigrationsAfterDatabaseRefreshed()
$table->integer('created_at');
$table->integer('updated_at');
});

Schema::create('users_nullable_timestamps', function ($table) {
$table->increments('id');
$table->string('email')->unique();
$table->timestamp('created_at')->nullable();
$table->timestamp('updated_at')->nullable();
});
}

protected function destroyDatabaseMigrations()
Expand Down Expand Up @@ -115,6 +122,27 @@ public function testItCastTimestampsCreatedByTheBuilderWhenTimeHasPassed()
$this->assertSame($updatedAt, $mutatorUser->updated_at->timestamp);
$this->assertSame($updatedAt, $mutatorUser->fresh()->updated_at->timestamp);
}

public function testItCastTimestampsUpdatedByAMutator()
{
Carbon::setTestNow(now());

$mutatorUser = UserWithUpdatedAtViaMutator::create([
'email' => fake()->unique()->email,
]);

$this->assertNull($mutatorUser->updated_at);

Carbon::setTestNow(now()->addSecond());
$updatedAt = now()->timestamp;

$mutatorUser->update([
'email' => fake()->unique()->email,
]);

$this->assertSame($updatedAt, $mutatorUser->updated_at->timestamp);
$this->assertSame($updatedAt, $mutatorUser->fresh()->updated_at->timestamp);
}
}

class UserWithIntTimestampsViaCasts extends Model
Expand Down Expand Up @@ -191,3 +219,19 @@ protected function setCreatedAtAttribute($value)
$this->attributes['created_at'] = Carbon::parse($value)->timestamp;
}
}

class UserWithUpdatedAtViaMutator extends Model
{
protected $table = 'users_nullable_timestamps';

protected $fillable = ['email', 'updated_at'];

public function setUpdatedAtAttribute($value)
{
if (! $this->id) {
return;
}

$this->updated_at = $value;
}
}