[7.x] Fix MorphPivot::delete for models with primary key #32421
Merged
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Hi,
I encounter problems when I try to delete models that extend
Illuminate\Database\Eloquent\Relations\MorphPivot
. I am by no means experienced with Laravel core development but I think I figured out what the root cause of the issue is. It is just a few lines of code, so instead of filing a bug report I offer this pull request with my solution for the experienced Laravel developers to check.If new tests are required for this situation, I would also kindly ask those of you who are familiar with developing for the framework for help because I did not find much information on the standards of testing in the contribution guide.
Thanks for your help!
The problem from a user's perspective
Consider the following two pivot models:
Both models are equipped with their own primary key
id
. The table structures look something like this:Now, when I instantiate the models and try to delete them, their behavior differs:
The exception looks like this:
Apparently, the name of the primary id column does not find its way into the query for the
MyMorphPivotModel
while the equivalent delete-operation forMyPivotModel
works just fine.Tentative solution
When trying to track the problem down, I compared the
delete
methods ofPivot
andMorphPivot
.Pivot
get itsdelete
method fromIlluminate\Database\Eloquent\Relations\Concerns\AsPivot
, which looks like this:MorphPivot
has its owndelete
method:The obvious difference is that
Pivot::delete
has a fallback toparent::delete
if a primary key attribute is set, whileMorphPivot::delete
lacks this construction. In the light of the aforementioned problems with the name of the primary key, this difference is worth a closer look.Adding the lines
at the beginning of
MorphPivot::delete
makes the problem disappear and makesPivot::delete
andMorphPivot::delete
more symmetric.The addition of these lines is just what this pull request is about.