Lately, I’ve been messing around with Laravel and while building a component for my application I’ve noticed that Laravel doesn’t generate a url with query strings. The “pretty urls” work just fine example.com/search/term
, but what I really needed in my case was url with a query string like example.com?search=term
.
For the purposes of this blog post, I choose a basic example of indexing all movies stored in our database and filtering the data based on movie’s name.
Install query-filters
I’ve found other packages for the same purpose, but decided to stick with this one since it was most recently updated. To install the query-filters package, open the command line from the root of your project and run the following command:
composer require cerbero/query-filters
Usage
Once the installation is finished, a filter that will filter the data based on the query string should be created. That can be easily done just by extending the QueryFilters
class.
The name of the query string actually corresponds to the method in this file, so our my url will look like /api/movies?name=Trainspotting
. Also, note that parameters having dashes or underscores will be converted into their respective camel case form. Basically, if we write /api/movies?movie_name=Trainspotting
it will look up for function movieName()
.
Additionally, we should let the model use the FiltersRecords
trait.
The last step is to write the method in the controller. Movies can be filtered by calling the method filterBy()
and passing an instance ofMovieFilters
. The code should look something like this:
The route.
Calling /api/movies
will return all movies from our database. Filtering the results by name could be done by adding the query string /api/movies?name=Trainspotting
.
References
Note: The latest version of Laravel when this blog post is written is 5.2. I’m also using MongoDB.