Skip to content

Commit

Permalink
[10.x] Fix issues with updated_at (#48230)
Browse files Browse the repository at this point in the history
* wip

* wip
  • Loading branch information
driesvints authored Aug 29, 2023
1 parent b40d6be commit d3b981b
Show file tree
Hide file tree
Showing 2 changed files with 45 additions and 1 deletion.
2 changes: 1 addition & 1 deletion src/Illuminate/Database/Eloquent/Builder.php
Original file line number Diff line number Diff line change
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
Original file line number Diff line number Diff line change
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;
}
}

0 comments on commit d3b981b

Please sign in to comment.