Member-only story
Dynamic Filters With Laravel Eloquent

Did you ever had a Laravel application and needs filters over your API? You might have tried GraphQL, however, you could write a simple one and don’t need any integrations.
In this article I’m going to implement a simple service which could work with Laravel eloquent ORM, it would handle relations and also the basic operators which uses the most.
The Idea
You are developing a RESTful API and want to let your users filter the indexes with different fields or even on the relations of your model.
For instance, a simple article
model which has so many tags
and comments
, also a user
who owns it. Now you have an API which lists all the articles /api/articles
. How could you let the user filter over the tags or comments? How could you filter all the articles of a specific user? Moreover, how could you combine all of them together?
Let’s add a filter to our API to find all the articles of user with id = 1.
/api/articles?filters[]=user.id=1
Seems cool? Now I want the articles of user 1 which have a specific tag.
/api/articles?filters[]=user.id=1&filters[]=tags.name=ipsa
In the next step, we are going to setup the basic project and then start adding these dynamic filters to that.
Setup
I was looking for a real world sample project and found out there is a complete Laravel application which could be used. Take a look at their github repository and walk through the README to set it up.
https://github.com/gothinkster/laravel-realworld-example-app
Extend the Idea
We know that there is a query param called filters
which contains the relation/field, operator and the value.
Here we are going to implement the basic logical operators which are =
, !=
, >
, <
, >=
and <=
. Also I have added 2 custom operators ~
and ()
.
~
would work as LIKE
in queries with %
around it.
e.x. /api/articles?filters[]=slug~real-world
SQL: SELECT * FROM articles where slug like '%real-world%';