Add more helpful error messages on bad or insufficient morphTo data #1824
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.
Introduction
This adds more descriptive error messages when eager loading morphTo relations with bad or insufficient data. Also fixes an error about destructuring assignment when the target polymorphic couldn't be found, that prevented the actual expected error from being thrown.
Motivation
The current error is only thrown when the defined morph type can't be found in any of the possible target types, but the message is a bit ambiguous because it only says that the target model can't be found.
Additionally the changes proposed in the previous PR would introduce other potential issues. It's also not very clear that having a different behavior for a polymorphic relation when calling
.related()
is a bad thing, as argued in that PR, since polymorphic relations are a bit different from the others.That PR also didn't include tests and its author was not responding.
Proposed solution
This adds an earlier check to see if the type attribute is set at all on the model and throws an error if it isn't. This is done before even attempting to find the target model from the defined target types.
The error message in case a valid target is not found is also reworded to make it clearer.
This is a breaking change since the existing error message is different and there is a new error being thrown.
Closes #656.
Current PR Issues
There is no check to see if the target id is set on the model since
NULL
can be a valid value, although it probably isn't. This check can easily be added in the future if needed.