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!
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:
Add domain/module support
#53
With this feature, now we can how multiple filters in multiple directories to support domain/module directory structure. For detailed information, please read the documentation (customize-per-domain/module section).
This PR will closed issue #51
Top comments (0)