Skip to content

Commit 6c5ecc1

Browse files
authored
[9.x] Fix default pivot attributes (#40947)
* [9.x] Fix default pivot attributes * Add test
1 parent 11251f2 commit 6c5ecc1

File tree

2 files changed

+18
-1
lines changed

2 files changed

+18
-1
lines changed

src/Illuminate/Database/Eloquent/Relations/Concerns/AsPivot.php

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -76,7 +76,9 @@ public static function fromRawAttributes(Model $parent, $attributes, $table, $ex
7676

7777
$instance->timestamps = $instance->hasTimestampAttributes($attributes);
7878

79-
$instance->setRawAttributes($attributes, $exists);
79+
$instance->setRawAttributes(
80+
array_merge($instance->getRawOriginal(), $attributes), $exists
81+
);
8082

8183
return $instance;
8284
}

tests/Integration/Database/EloquentCustomPivotCastTest.php

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -137,6 +137,17 @@ public function testCastsAreRespectedOnSyncArrayWhileUpdatingExisting()
137137
$this->assertEquals(['foo1' => 'bar1'], $project->collaborators[0]->pivot->permissions);
138138
$this->assertEquals(['baz2' => 'bar2'], $project->collaborators[1]->pivot->permissions);
139139
}
140+
141+
public function testDefaultAttributesAreRespectedAndCastsAreRespected()
142+
{
143+
$project = CustomPivotCastTestProject::forceCreate([
144+
'name' => 'Test Project',
145+
]);
146+
147+
$pivot = $project->collaborators()->newPivot();
148+
149+
$this->assertEquals(['permissions' => ['create', 'update']], $pivot->toArray());
150+
}
140151
}
141152

142153
class CustomPivotCastTestUser extends Model
@@ -160,6 +171,10 @@ public function collaborators()
160171

161172
class CustomPivotCastTestCollaborator extends Pivot
162173
{
174+
protected $attributes = [
175+
'permissions' => '["create", "update"]',
176+
];
177+
163178
protected $casts = [
164179
'permissions' => 'json',
165180
];

0 commit comments

Comments
 (0)