Making the advanced search query with Eloquent-Builder in Laravel

Image for post
Image for post
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?

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

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:

//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 more details check out the GitHub repository.

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

Written by

Software Designer and Back-End Developer

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store