Skip to content
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.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 6 additions & 0 deletions src/Eloquent/Builder.php
Original file line number Diff line number Diff line change
Expand Up @@ -204,6 +204,12 @@ public function createOrFirst(array $attributes = [], array $values = []): Model
// Apply casting and default values to the attributes
// In case of duplicate key between the attributes and the values, the values have priority
$instance = $this->newModelInstance($values + $attributes);

/* @see \Illuminate\Database\Eloquent\Model::performInsert */
if ($instance->usesTimestamps()) {
$instance->updateTimestamps();
}

$values = $instance->getAttributes();
$attributes = array_intersect_key($attributes, $values);

Expand Down
9 changes: 9 additions & 0 deletions tests/ModelTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -1048,12 +1048,17 @@ public function testNumericFieldName(): void

public function testCreateOrFirst()
{
Carbon::setTestNow('2010-06-22');
$createdAt = Carbon::now()->getTimestamp();
$user1 = User::createOrFirst(['email' => '[email protected]']);

$this->assertSame('[email protected]', $user1->email);
$this->assertNull($user1->name);
$this->assertTrue($user1->wasRecentlyCreated);
$this->assertEquals($createdAt, $user1->created_at->getTimestamp());
$this->assertEquals($createdAt, $user1->updated_at->getTimestamp());

Carbon::setTestNow('2020-12-28');
$user2 = User::createOrFirst(
['email' => '[email protected]'],
['name' => 'John Doe', 'birthday' => new DateTime('1987-05-28')],
Expand All @@ -1064,6 +1069,8 @@ public function testCreateOrFirst()
$this->assertNull($user2->name);
$this->assertNull($user2->birthday);
$this->assertFalse($user2->wasRecentlyCreated);
$this->assertEquals($createdAt, $user1->created_at->getTimestamp());
$this->assertEquals($createdAt, $user1->updated_at->getTimestamp());

$user3 = User::createOrFirst(
['email' => '[email protected]'],
Expand All @@ -1075,6 +1082,8 @@ public function testCreateOrFirst()
$this->assertSame('Jane Doe', $user3->name);
$this->assertEquals(new DateTime('1987-05-28'), $user3->birthday);
$this->assertTrue($user3->wasRecentlyCreated);
$this->assertEquals($createdAt, $user1->created_at->getTimestamp());
$this->assertEquals($createdAt, $user1->updated_at->getTimestamp());

$user4 = User::createOrFirst(
['name' => 'Robert Doe'],
Expand Down