Skip to content

Adding pivot values causes the pivot model observer not work properly #55026

@amir9480

Description

@amir9480

Laravel Version

12.2.0

PHP Version

8.3.6

Database Driver & Version

No response

Description

Suppose we have a many-to-many relationship with a custom pivot model class. In that case, we can use an observer to handle events for the pivot model (and the relationship).

But here is the issue. If I add a withPivotValue to my relationship, the update and delete events will not work anymore.

Steps To Reproduce

In my project, I have a many to many relation like this:
app/Models/Project.php

class Project // ...
{
    public function allMembers(): BelongsToMany
    {
        return $this->belongsToMany(User::class, 'project_members')
            ->withPivot(...)
            ->using(ProjectMember::class);
    }

    public function members(): BelongsToMany
    {
        return $this->allMembers()->withPivotValue('role', 'member');
    }

    public function managers(): BelongsToMany
    {
        return $this->allMembers()->withPivotValue('role', 'manager');
    }
}

I have an observer for the project member model like this:

class ProjectMemberObserver
{
    public function created(ProjectMember $projectMember): void
    {
        dd('created called');
    }

    public function updated(ProjectMember $projectMember): void
    {
        dd('updated called');
    }

    public function deleted(ProjectMember $projectMember): void
    {
        dd('deletedcalled');
    }
}

Now, if I use the relation without the pivot value, my observer works as expected:

$project = Project::find(...);

$project->allMembers()->attach(...); // created called
$project->allMembers()->updateExistingPivot(..., [...]); // updated called
$project->allMembers()->detach(...); // deleted called

But if I use the relation with pivot value, only the create handler will work, and the updated or deleted will not work as expected.

$project = Project::find(...);

$project->managers()->attach(...); // created called
$project->managers()->updateExistingPivot(..., [...]); // Observer not working
$project->managers()->detach(...); // Observer not working

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions