Laravel: One unfamiliar but effective way of implementing filters in Eloquent

Joy Debnath
3 min readAug 4, 2021

--

Here is the scenario, you want to get the list of uses based on certain filters. For instance, give me all users where age is between 10 to 20 and status is active.

This seems simple and manageable. Add a few “if else” clauses to build your eloquent query and you are done! Your web application is doing great and your clients just love it…

But few months forward, you need to add more filters, and more complicated business logics. Next minute, your function is few hundred lines long and debugging is a nightmare! You must be wondering now, what is the best way to deal with this?

Now, let me ask you, have you heard about pipeline? Pipeline is a beautiful OOP design pattern. The name itself is kind of self explanatory. You send your object into the pipe where the object goes through few tasks before it reaches the final form.

You don’t need any package to install to use Pipeline as Laravel has this baked-in for long time. We can leverage this to construct our User Eloquent Query for filtering.

Let’s build a users filter using Pipeline.

Following is my way of organizing the filter pipes and you can choose whatever works best for you. I have create a filters folder under app directory. There I have Pipe interface which will be implemented by all the filters. This way, I make sure all filter pipe objects implement the required function.

pipe.php file under app/filters directory
pipe.php file under app/filters directory

Now I will create two filter pipes that will be responsible for adding age and status filter on user eloquent query builder.

The implementation of UserAgeFilter.php under app\filter\user directory
The implementation of UserUserFilter.php under app\filter\user directory

Finally, it’s time to write our function that implements the Pipeline. We have to use app() function to get an instance of Pipeline object.

The implementation of Pipeline to filter users data

Here, I send the User query builder through the pipeline, which will go through UserAgeFilter and UserStatusFilter pipes and the apply function on each of these pipes will be executed. After $users go through all the pipes, we get the final query. Finally, we call the get function to retrieve the records that match the filters.

For the reference, here is what the User resource file looks like

Implementation of User resource

And just like that we can implement a simple and manageable filtering process using Pipeline.

--

--