Skip to content

Commit 491b9c3

Browse files
committed
PHPORM-171 Set timestamps when using createOrFirst
1 parent 8f7bf77 commit 491b9c3

File tree

2 files changed

+15
-0
lines changed

2 files changed

+15
-0
lines changed

src/Eloquent/Builder.php

+6
Original file line numberDiff line numberDiff line change
@@ -204,6 +204,12 @@ public function createOrFirst(array $attributes = [], array $values = []): Model
204204
// Apply casting and default values to the attributes
205205
// In case of duplicate key between the attributes and the values, the values have priority
206206
$instance = $this->newModelInstance($values + $attributes);
207+
208+
/* @see \Illuminate\Database\Eloquent\Model::performInsert */
209+
if ($instance->usesTimestamps()) {
210+
$instance->updateTimestamps();
211+
}
212+
207213
$values = $instance->getAttributes();
208214
$attributes = array_intersect_key($attributes, $values);
209215

tests/ModelTest.php

+9
Original file line numberDiff line numberDiff line change
@@ -1048,12 +1048,17 @@ public function testNumericFieldName(): void
10481048

10491049
public function testCreateOrFirst()
10501050
{
1051+
Carbon::setTestNow('2010-06-22');
1052+
$createdAt = Carbon::now()->getTimestamp();
10511053
$user1 = User::createOrFirst(['email' => 'john.doe@example.com']);
10521054

10531055
$this->assertSame('john.doe@example.com', $user1->email);
10541056
$this->assertNull($user1->name);
10551057
$this->assertTrue($user1->wasRecentlyCreated);
1058+
$this->assertEquals($createdAt, $user1->created_at->getTimestamp());
1059+
$this->assertEquals($createdAt, $user1->updated_at->getTimestamp());
10561060

1061+
Carbon::setTestNow('2020-12-28');
10571062
$user2 = User::createOrFirst(
10581063
['email' => 'john.doe@example.com'],
10591064
['name' => 'John Doe', 'birthday' => new DateTime('1987-05-28')],
@@ -1064,6 +1069,8 @@ public function testCreateOrFirst()
10641069
$this->assertNull($user2->name);
10651070
$this->assertNull($user2->birthday);
10661071
$this->assertFalse($user2->wasRecentlyCreated);
1072+
$this->assertEquals($createdAt, $user1->created_at->getTimestamp());
1073+
$this->assertEquals($createdAt, $user1->updated_at->getTimestamp());
10671074

10681075
$user3 = User::createOrFirst(
10691076
['email' => 'jane.doe@example.com'],
@@ -1075,6 +1082,8 @@ public function testCreateOrFirst()
10751082
$this->assertSame('Jane Doe', $user3->name);
10761083
$this->assertEquals(new DateTime('1987-05-28'), $user3->birthday);
10771084
$this->assertTrue($user3->wasRecentlyCreated);
1085+
$this->assertEquals($createdAt, $user1->created_at->getTimestamp());
1086+
$this->assertEquals($createdAt, $user1->updated_at->getTimestamp());
10781087

10791088
$user4 = User::createOrFirst(
10801089
['name' => 'Robert Doe'],

0 commit comments

Comments
 (0)