Making the advanced search query with Eloquent-Builder in Laravel

Photo by Anthony Ginsbrook on Unsplash

We needed an advanced search system in the recent project.This system included many filters that required a flexible and scalable search system.

I decided to implement a package for this system that you can see it in the GitHub and use it in your project.

What’s the problem?

The problem is that you will encounter with a set of filters that you must check for a lot of conditions to add to the query.

Writing a lot of terms will surely reduce the readability of your code and slow down the development process.

Also, you can only use the filters and terms in the same scope and they will not be reusable.

But the Solution

You must Refactor your code!

To solve this problem, you need to Refactor your code by replacing many of your conditionals with polymorphism.

Click here to learn more about this design pattern.

Practical example:

Suppose we want to get the list of the users with the requested parameters as follows:

//GET users/search?age_more_than=25&gender=male&has_published_post=true

The Requested parameter will be as follows:

'age_more_than' => '25',
'gender' => 'male',
'has_published_post' => 'true',

In the legacy code the method written below was followed:

We check out a condition for each request parameter.

In the future, we will have more parameters that should be checked and applied in the code above that causes us to have a dirty code.

Use the Eloquent-Builder to resolve the problem

After installing the package presented,change your code as follows:

You just send the model and parameters to ‘to’ method.Then, you need to define the filter for each parameter that you want to add to the query.

So easy!

Defining a filter

For example, I’ll implement one of the above example filters. Follow the example below:

For more details check out the GitHub repository.

Good luck and thank you for sharing your valuable time with me.