Laravel Eloquent Filter (All in one)

fouladgar.dev
3 min readJan 1, 2020

Have you ever stuck in a situation which a lot of parameters should be send to your API? and you must create tons of queries based on them? If your answer is yes, do not stop reading!

GitHub Repository: https://github.com/mohammad-fouladgar/eloquent-builder

First of all, if you haven’t read This article about Eloquent filters before, I strongly advise you to take a look at it. In the mentioned article you will learn how to make advance query filters for your Eloquent model.

Also, You may need a secure filter. Secure filters will authorize the user for applying a given filter, which you can find the related article here.

Now, what if your Laravel project is not following default directory structure?

Define Filters Per Domain/Module

In a small Laravel project, you can use the default architecture (MVC) and its respective directory structure as below:

.
├── app
│ ├── Console
├── EloquentFilters // Default directory for filters
│ └── Product
│ ├── PriceMoreThanFilter.php
│ └── User
│ ├── AgeMoreThanFilter.php
│ └── GenderFilter.php
└── Exceptions
│ ├── Http
│ │ ├── Controllers
│ │ ├── Middleware
│ │ └── Requests
│ └── Providers
├── bootstrap
├── config
├── database
├── public
├── resources
├── routes
├── storage

And you can using EloquentBuilder like this:

But when your project grows by the time, the default structure is not enough. Eventually, this problem leads you to use a different architecture (i.e. Domain-Driven-Desgin, HMVC, …) or modifying current one. Therefore changing the directory structure in inevitable. Take a look at this one:

.
├── app
├── bootstrap
├── config
├── database
├── Domains
│ ├── Product
│ │ ├── database
│ │ │ └── migrations
│ │ ├── src
│ │ ├── Filters //Custom directory for Product model filters
│ │ │ └── PriceMoreThanFilter.php
│ │ ├── Entities
│ │ ├── Http
│ │ └── Controllers
│ │ ├── routes
│ │ └── Services
│ ├── User
│ │ ├── database
│ │ │ └── migrations
│ │ ├── src
│ │ ├── Filters //Custom directory for User model filters
│ │ │ └── AgeMoreThanFilter.php
│ │ ├── Entities
│ │ ├── Http
│ │ └── Controllers
│ │ ├── routes
│ │ └── Services
...

In this week, EloquentBuilder v2.0 has been released. In this version a new setFilterNamespace method added to the package to let you create custom filters “per domain/module” by setting filters namespace of the fly.

Now we can use filters for each model as below:

Conclusion

Dealing with API incoming parameters is a tedious job, so getting help from a black box package helps you to handle them without any concern and complexity. Furthermore, now there is a possibility to use this advantage in larger projects with different structures.

Special thanks to 50bhan for this awesome PR:

--

--