Skip to content

Commit d3b981b

Browse files
authored
[10.x] Fix issues with updated_at (#48230)
* wip * wip
1 parent b40d6be commit d3b981b

File tree

2 files changed

+45
-1
lines changed

2 files changed

+45
-1
lines changed

src/Illuminate/Database/Eloquent/Builder.php

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1166,7 +1166,7 @@ protected function addUpdatedAtColumn(array $values)
11661166
) {
11671167
$timestamp = $this->model->newInstance()
11681168
->forceFill([$column => $timestamp])
1169-
->getAttributes()[$column];
1169+
->getAttributes()[$column] ?? $timestamp;
11701170
}
11711171

11721172
$values = array_merge([$column => $timestamp], $values);

tests/Integration/Database/MySql/EloquentCastTest.php

Lines changed: 44 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -20,6 +20,13 @@ protected function defineDatabaseMigrationsAfterDatabaseRefreshed()
2020
$table->integer('created_at');
2121
$table->integer('updated_at');
2222
});
23+
24+
Schema::create('users_nullable_timestamps', function ($table) {
25+
$table->increments('id');
26+
$table->string('email')->unique();
27+
$table->timestamp('created_at')->nullable();
28+
$table->timestamp('updated_at')->nullable();
29+
});
2330
}
2431

2532
protected function destroyDatabaseMigrations()
@@ -115,6 +122,27 @@ public function testItCastTimestampsCreatedByTheBuilderWhenTimeHasPassed()
115122
$this->assertSame($updatedAt, $mutatorUser->updated_at->timestamp);
116123
$this->assertSame($updatedAt, $mutatorUser->fresh()->updated_at->timestamp);
117124
}
125+
126+
public function testItCastTimestampsUpdatedByAMutator()
127+
{
128+
Carbon::setTestNow(now());
129+
130+
$mutatorUser = UserWithUpdatedAtViaMutator::create([
131+
'email' => fake()->unique()->email,
132+
]);
133+
134+
$this->assertNull($mutatorUser->updated_at);
135+
136+
Carbon::setTestNow(now()->addSecond());
137+
$updatedAt = now()->timestamp;
138+
139+
$mutatorUser->update([
140+
'email' => fake()->unique()->email,
141+
]);
142+
143+
$this->assertSame($updatedAt, $mutatorUser->updated_at->timestamp);
144+
$this->assertSame($updatedAt, $mutatorUser->fresh()->updated_at->timestamp);
145+
}
118146
}
119147

120148
class UserWithIntTimestampsViaCasts extends Model
@@ -191,3 +219,19 @@ protected function setCreatedAtAttribute($value)
191219
$this->attributes['created_at'] = Carbon::parse($value)->timestamp;
192220
}
193221
}
222+
223+
class UserWithUpdatedAtViaMutator extends Model
224+
{
225+
protected $table = 'users_nullable_timestamps';
226+
227+
protected $fillable = ['email', 'updated_at'];
228+
229+
public function setUpdatedAtAttribute($value)
230+
{
231+
if (! $this->id) {
232+
return;
233+
}
234+
235+
$this->updated_at = $value;
236+
}
237+
}

0 commit comments

Comments
 (0)