Skip to content

[12.x] Fix pivot model events not working when using the withPivotValue #55280

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 2 commits into from
Apr 11, 2025
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
Original file line number Diff line number Diff line change
Expand Up @@ -207,18 +207,15 @@ protected function attachNew(array $records, array $current, $touch = true)
*/
public function updateExistingPivot($id, array $attributes, $touch = true)
{
if ($this->using &&
empty($this->pivotWheres) &&
empty($this->pivotWhereIns) &&
empty($this->pivotWhereNulls)) {
if ($this->using) {
return $this->updateExistingPivotUsingCustomClass($id, $attributes, $touch);
}

if ($this->hasPivotColumn($this->updatedAt())) {
$attributes = $this->addTimestampsToAttachment($attributes, true);
}

$updated = $this->newPivotStatementForId($this->parseId($id))->update(
$updated = $this->newPivotStatementForId($id)->update(
$this->castAttributes($attributes)
);

Expand All @@ -239,10 +236,7 @@ public function updateExistingPivot($id, array $attributes, $touch = true)
*/
protected function updateExistingPivotUsingCustomClass($id, array $attributes, $touch)
{
$pivot = $this->getCurrentlyAttachedPivots()
->where($this->foreignPivotKey, $this->parent->{$this->parentKey})
->where($this->relatedPivotKey, $this->parseId($id))
->first();
$pivot = $this->getCurrentlyAttachedPivotsForIds($id)->first();

$updated = $pivot ? $pivot->fill($attributes)->isDirty() : false;

Expand Down Expand Up @@ -435,11 +429,7 @@ public function hasPivotColumn($column)
*/
public function detach($ids = null, $touch = true)
{
if ($this->using &&
! empty($ids) &&
empty($this->pivotWheres) &&
empty($this->pivotWhereIns) &&
empty($this->pivotWhereNulls)) {
if ($this->using) {
$results = $this->detachUsingCustomClass($ids);
} else {
$query = $this->newPivotQuery();
Expand Down Expand Up @@ -480,11 +470,21 @@ protected function detachUsingCustomClass($ids)
{
$results = 0;

foreach ($this->parseIds($ids) as $id) {
$results += $this->newPivot([
$this->foreignPivotKey => $this->parent->{$this->parentKey},
$this->relatedPivotKey => $id,
], true)->delete();
if (! empty($this->pivotWheres) ||
! empty($this->pivotWhereIns) ||
! empty($this->pivotWhereNulls)) {
$records = $this->getCurrentlyAttachedPivotsForIds($ids);

foreach ($records as $record) {
$results += $record->delete();
}
} else {
foreach ($this->parseIds($ids) as $id) {
$results += $this->newPivot([
$this->foreignPivotKey => $this->parent->{$this->parentKey},
$this->relatedPivotKey => $id,
], true)->delete();
}
}

return $results;
Expand All @@ -497,15 +497,31 @@ protected function detachUsingCustomClass($ids)
*/
protected function getCurrentlyAttachedPivots()
{
return $this->newPivotQuery()->get()->map(function ($record) {
$class = $this->using ?: Pivot::class;

$pivot = $class::fromRawAttributes($this->parent, (array) $record, $this->getTable(), true);
return $this->getCurrentlyAttachedPivotsForIds();
}

return $pivot
->setPivotKeys($this->foreignPivotKey, $this->relatedPivotKey)
->setRelatedModel($this->related);
});
/**
* Get the pivot models that are currently attached, filtered by related model keys.
*
* @param mixed $ids
* @return \Illuminate\Support\Collection
*/
protected function getCurrentlyAttachedPivotsForIds($ids = null)
{
return $this->newPivotQuery()
->when(! is_null($ids), fn ($query) => $query->whereIn(
$this->getQualifiedRelatedPivotKeyName(), $this->parseIds($ids)
))
->get()
->map(function ($record) {
$class = $this->using ?: Pivot::class;

$pivot = $class::fromRawAttributes($this->parent, (array) $record, $this->getTable(), true);

return $pivot
->setPivotKeys($this->foreignPivotKey, $this->relatedPivotKey)
->setRelatedModel($this->related);
});
}

/**
Expand Down Expand Up @@ -557,7 +573,7 @@ public function newPivotStatement()
*/
public function newPivotStatementForId($id)
{
return $this->newPivotQuery()->whereIn($this->relatedPivotKey, $this->parseIds($id));
return $this->newPivotQuery()->whereIn($this->getQualifiedRelatedPivotKeyName(), $this->parseIds($id));
}

/**
Expand Down
35 changes: 35 additions & 0 deletions tests/Integration/Database/EloquentPivotEventsTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -74,6 +74,34 @@ public function testPivotWillTriggerEventsToBeFired()
$this->assertEquals(['deleting', 'deleted'], PivotEventsTestCollaborator::$eventsCalled);
}

public function testPivotWithPivotValueWillTriggerEventsToBeFired()
{
$user = PivotEventsTestUser::forceCreate(['email' => '[email protected]']);
$user2 = PivotEventsTestUser::forceCreate(['email' => '[email protected]']);
$project = PivotEventsTestProject::forceCreate(['name' => 'Test Project']);

$project->managers()->attach($user);
$this->assertEquals(['saving', 'creating', 'created', 'saved'], PivotEventsTestCollaborator::$eventsCalled);
$project->managers()->attach($user2);

PivotEventsTestCollaborator::$eventsCalled = [];
$project->managers()->updateExistingPivot($user->id, ['permissions' => ['foo', 'bar']]);
$this->assertEquals(['saving', 'updating', 'updated', 'saved'], PivotEventsTestCollaborator::$eventsCalled);
$project->managers()->detach($user2);

PivotEventsTestCollaborator::$eventsCalled = [];
$project->managers()->sync([$user2->id]);
$this->assertEquals(['deleting', 'deleted', 'saving', 'creating', 'created', 'saved'], PivotEventsTestCollaborator::$eventsCalled);

PivotEventsTestCollaborator::$eventsCalled = [];
$project->managers()->sync([$user->id => ['permissions' => ['foo']], $user2->id => ['permissions' => ['bar']]]);
$this->assertEquals(['saving', 'creating', 'created', 'saved', 'saving', 'updating', 'updated', 'saved'], PivotEventsTestCollaborator::$eventsCalled);

PivotEventsTestCollaborator::$eventsCalled = [];
$project->managers()->detach($user);
$this->assertEquals(['deleting', 'deleted'], PivotEventsTestCollaborator::$eventsCalled);
}

public function testPivotWithPivotCriteriaTriggerEventsToBeFiredOnCreateUpdateNoneOnDetach()
{
$user = PivotEventsTestUser::forceCreate(['email' => '[email protected]']);
Expand Down Expand Up @@ -192,6 +220,13 @@ public function contributors()
->wherePivot('role', 'contributor');
}

public function managers()
{
return $this->belongsToMany(PivotEventsTestUser::class, 'project_users', 'project_id', 'user_id')
->using(PivotEventsTestCollaborator::class)
->withPivotValue('role', 'manager');
}

public function equipments()
{
return $this->morphToMany(PivotEventsTestEquipment::class, 'equipmentable')->using(PivotEventsTestModelEquipment::class);
Expand Down
Loading