[11.x] Add the ability to defer route model binding #54053
Closed
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.
I ran into the behavior that was reported in #44177 and am proposing this addition to help resolve it by deferring the query until the model is used.
To be clear: this changes no existing behavior. There is a single thing I couldn't resolve with this, which is that when using scoped bindings only the final child model will end up being deferred. I don't think this is a big deal, but it would be great if the entire chain could be deferred — the problem is there's no way to get the relationship to figure out the child model without it pulling the
id
of the parent and that implicitly resolves the parent.This probably should just be a package, but I wanted to see if there was interest in including it in the core framework first.
Here's a draft attempt at docs to explain it:
Deferred Binding
By default, models are resolved before route middleware has been executed, this means that any global scopes applied to the model that rely on data created in middleware will not function as expected.
To resolve this, you can use the
DeferRouteBinding
trait. When used in your models, the query is deferred when binding until either explicitly or implicitly loaded within the method itself:You should ensure to load the model prior to executing any other code that would later fail if the model is not found.
Note: when using scoped bindings, only the final "child" model will be deferred.