Junior Grossi has posted a tutorial that covers the idea of data filtering with Eloquent models. In this case, the filtering is based on user input from a URL with parameters matching the properties on the model.
Filtering models was, for a very long time, a hard task for me. I admit that I could not think in some easy way to do that. I tried, refactored some code, created custom classes for that, but I never thought how this could be easily implemented.Watching a Laracast’s video from 2016 about the Laravel’s Eloquent ORM I faced of with a bunch of classes and a trait that removed a lot of trash from my controller actions. That was called by Jeffrey Way the QueryFilter.
He then gets into some of the goals behind the filtering and the expected input method (URL parameters). He then creates a simple Laravel application making use of Corcel to integrate with his current WordPress backend database. He includes code examples showing the creation of a Post
model and controller and returning only the desired fields using a JSON response and a toArray
method. He then moves on to the filtering, starting with a more hard-coded version of the search: adding a where
statement to the query manually before the get
.
To replace this with something more flexible, he implements the QueryFilter
class that can be extended to match the requirements for the model type. He then implements the PostFilter
class, adding methods for "status" and "title" fields. Finally he adds in a scopeFilter
method that makes it simpler to call the filtering directly from the model instance.