#database #development #eloquent #laravel #php #reading-list

πŸ”— One unfamiliar but effective way of implementing filters in Eloquent

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.

continue reading on medium.com

⚠️ This post links to an external website. ⚠️