[10.x] Refines Queries from Request #49611
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.
What?
This is a relatively big-but-small PR that adds the ability to "refine" a query. This allows to refine a database query based on the request query by moving that logic away from the controller. This PR adds the
illuminate/refine
package for the main reason it depends on bothilluminate/database
andilluminate/http
.For example, let's imagine we want to filter the posts safely from the database from this request:
The normal way to filter that would be to push that logic into the controller itself:
The controller will grow in size at the same time more query keys are expected to manage the query, especially when managing virtual states of models (that are equivalent to multiple WHERE clauses on multiple columns), and adding gates to check if the user can use a given key.
Instead, we could move all that logic into what I define as a "Refiner". This class is relatively simple to understand: for each key present in the Request, call the matching method (in
camelCase
) on the Refiner class.All the logic is moved down to the "Refiner" class. That class is resolved by the container. That class is managed opaquely by another class (the "Query Refiner") that injects the current Request and the calls over that aforementioned Refiner matching methods.
That Refiner looks like this:
Not only we moved the refinement outside controller, it also moves the condition away from the actual refinement logic.
The Refiner also allows to execute something on the Builder and Request before and after with the
before()
andafter()
method, respectively.Finally, not every request will require all the keys. The developer can choose to limit the keys to use from the request using the
keys()
method. By default, it always returns all the keys from the Request, but in this following example it only checks for two keys.This PR also includes tests for the Refine, the
make:refiner
command (which creates a file onapp\Http\Refiners
) and its test.