[11.x] Add the pivot's related model when creating from attributes #53694
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.
Problem
For advanced model relationships where a custom pivot model has been created, the developer has the opportunity to define their own
fromRawAttributes
method.Within this they may wish to conduct certain actions depending on the relationship. For me, this is for the purpose of auditing.
Currently I am auditing all models through their events, including the pivots when extending the above class. However when I
attach
,detach
, orupdateExistingPivot
, I can only identify the parent with$pivot->pivotParent
. There is no way of knowing which relationship was called on the parent model so you don't know what was attached/detached/updated (which isn't ideal for an audit).For example:
$pivot->pivotParent
will be the User model, but the Pivot model doesn't know it's the Role model being attached.Whilst the pivot keys are set (so we have
role_id
anduser_id
), there is no reliable way to identify the pivot's "child" (related) as the column names could potentially not follow convention (e.g.parent_role
anduser
).As
$related
is only calculated on the relationship, you could not handle this infromRawAttributes
without overwriting all the core model methods that call it, which will increase upgrade friction.Solution
As we're already setting the
pivotParent
, I'm proposing we also set the related model (pivotRelated
) on the Pivot. Even though the relationship builds this as an empty class, it still helps developers reliably get the accurate class. This could easily be combined with$pivot->getAttribute($pivot->getRelatedKey())
to get the model's ID, then a fresh instance if required.Whilst I would prefer the property order to be slightly different so
$related
followed$parent
, this solution felt the least intrusive option so we can retain backwards compatibility and not introduce any breaking changes.Happy to look at alternative options though if I'm missing a simpler solution!