[12.x] Add pipe
method query builders
#55171
Merged
+73
−1
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.
This PR introduces a
pipe
method to the base query builder and eloquent query builder. The functionality of this method is the same as the collectionpipe
method.Why?
Model scopes offer the ability to return the result of a query. Scopes that execute the query and return a result I've personally dubbed action scopes. My blog post on the idea.
An action scope:
Usage:
You can consider native methods things like
count
,get
,pluck
, etc., to be built-in action scopes.When using the query builder directly for non-eloquent queries, I very much enjoy using tappable scopes for reusable query filtering.
Usage:
There is currently no way to create an action scope using this pattern.
Imagine you have many queries throughout your application's controllers that all have their own unique filtering and always end in a similar pattern: order, paginate, include query string, and map into an value object.
With the
pipe
method, it is possible to wrap this up into a reusable action scope:Query may now be refactored:
Aside from the above, I often find the
pipe
helper useful when building collection pipelines to inline some more complex logic related to the query that I otherwise would have to split out before the collection call chain.