承接 atldays/laravel-eloquent-filters 相关项目开发

从需求分析到上线部署,全程专人跟进,保证项目质量与交付效率

邮箱:yvsm@zunyunkeji.com | QQ:316430983 | 微信:yvsm316

atldays/laravel-eloquent-filters

Composer 安装命令:

composer require atldays/laravel-eloquent-filters

包简介

Advanced Laravel models filtering capabilities

README 文档

README

Latest Version on Packagist Total Downloads CI License: MIT

This package is maintained by Atldays and is based on a fork of the original pricecurrent/laravel-eloquent-filters package.

Installation

You can install the package via composer:

composer require atldays/laravel-eloquent-filters

Compatibility

The package currently supports Laravel 10, 11, 12, and 13.

Usage

This package gives you fine-grained control over how you may go about filtering your Eloquent Models.

This package is particularly good when you need to address complex use-cases, implementing filtering on many parameters, using complex logic.

But let's start with simple example:

Consider you have a Product, and you need to filter products by name:

use App\Filters\NameFilter;
use Atldays\EloquentFilters\EloquentFilters;

class ProductsController
{
    public function index(Request $request)
    {
        $filters = EloquentFilters::make([new NameFilter($request->name)]);

        $products = Product::filter($filters)->get();
    }
}

Generate eloquent-filter

php artisan make:eloquent-filter NameFilter

This will put your Filter to the app/Filters directory by default. You may prefix the name with the path, like Models/Product/NameFilter.

php artisan make:eloquent-filter Models/Product/NameFilter

You can use the --field=name argument to generate your filter with the field name

php artisan make:eloquent-filter Models/Product/NameFilter --field=name

Here is what your NameFilter might look like:

use Atldays\EloquentFilters\AbstractEloquentFilter;
use Illuminate\Database\Eloquent\Builder;

class NameFilter extends AbstractEloquentFilter
{
    protected $name;

    public function __construct($name)
    {
        $this->name = $name;
    }

    public function apply(Builder $query): Builder
    {
        return $query->where('name', 'like', "{$this->name}%");
    }
}

Notice how our Filter has no clue it is tied up with a specific Eloquent Model? That means, we can simply re-use it for any other model, where we need to bring in the same name filtering functionality:

use App\Filters\NameFilter;
use App\Models\User;
use Atldays\EloquentFilters\EloquentFilters;

class UsersController
{
    public function index(Request $request)
    {
        $filters = EloquentFilters::make([new NameFilter($request->user_name)]);

        $products = User::filter($filters)->get();
    }
}

You can chain methods from the filter as if it was simply an Eloquent Builder method:

use App\Filters\NameFilter;
use App\Models\User;
use Atldays\EloquentFilters\EloquentFilters;

class UsersController
{
    public function index(Request $request)
    {
        $filters = EloquentFilters::make([new NameFilter($request->user_name)]);

        $products = User::query()
            ->filter($filters)
            ->limit(10)
            ->latest()
            ->get();
    }
}

To enable filtering capabilities on an Eloquent Model simply import the trait Filterable

use Atldays\EloquentFilters\Filterable;
use Illuminate\Database\Eloquent\Model;

class Product extends Model
{
    use Filterable;
}

You may also pass a single filter or an array of filters directly:

Product::filter(new NameFilter($request->name))->get();

Product::filter([
    new NameFilter($request->name),
    new IsActiveFilter($request->boolean('active')),
])->get();

More complex use-case

This approach scales very well when you are dealing with a real-life larger applications where querying data from the DB goes far beyond simple comparison by a name field.

Consider an app where we have Stores with a Location coordinates and we have products in stock and we need to query all products that are in stock in a store that is in 10 miles radius

We may stuff all the logic in the controller with some pseudo-code:

class ProductsController
{
    public function index(Request $request)
    {
        $products Product::query()
            ->when($request->in_stock, function ($query) {
                $query->join('product_stock', fn ($q) => $q->on('product_stock.product_id', '=', 'products.id')->where('product_stock.quantity', '>', 0));
            })
            ->when($request->within_radius, function ($query) {
                $coordinates = auth()->user()->getCoordinates();
                $query->join('stores', 'stores.id', '=', 'product_stock.store_id');
                $query->whereRaw('
                    ST_Distance_Sphere(
                        Point(stores.longitude, stores.latitude),
                        Point(?, ?)
                    ) <= ?',
                    [$coordinates->longitude, $coordinates->latitude, $query->within_radius]
                );

            })
            ->get();

        return response()->json(['data' => $products]);
    }
}

This breaks Open-Closed principle and makes the code harder to test and maintain. Adding new functionality becomes a disaster.

class ProductsController
{
    public function index(Request $request)
    {
        $filters = EloquentFilters::make([
            new ProductInStockFilter($request->in_stock),
            new StoreWithinDistanceFilter($request->within_radius, auth()->user()->getCoordinates())
        ]);

        $products = Product::filter($filters)->get();

        return response()->json(['data' => $products]);
    }
}

Much Better!

We can now distribute the filtering logic to a dedicated class

class StoreWithinDistanceFilter extends AbstractEloquentFilter
{
    public function __construct($distance, Coordinates $fromCoordinates)
    {
        $this->distance = $distance;
        $this->fromCoordinates = $fromCoordinates;
    }

    public function apply(Builder $query): Builder
    {
        return $builder->join('stores', 'stores.id', '=', 'product_stock.store_id')
            ->whereRaw('
                ST_Distance_Sphere(
                    Point(stores.longitude, stores.latitude),
                    Point(?, ?)
                ) <= ?',
                [$this->coordinates->longitude, $this->coordinates->latitude, $this->distance]
            );
    }
}

Now we have no problem with testing our functionality

class StoreWithinDistanceFilterTest extends TestCase
{
    /**
     * @test
     */
    public function it_filters_products_by_store_distance()
    {
        $user = User::factory()->create(['latitude' => '...', 'longitude' => '...']);
        $store = Store::factory()->create(['latitude' => '...', 'longitude' => '...']);
        $products = Product::factory()->create();
        $store->stock()->attach($product, ['quantity' => 3]);

        $result = Product::filter(new EloquentFilters([new StoreWithinDistanceFilter(10, $user->getCoordinates())]));

        $this->assertCount(1, $result);
    }
}

And controller can be just tested with mocks or stubs, just making sure we have called the necessary filters.

Checking filtering is applicable

Each filter provides method isApplicable() which you might implement and return boolean. If false is returned, the apply method won't be called.

This is helpful when we don't control the incoming parameters to the filter class. In the example above we can do something like this:

class StoreWithinDistanceFilter extends AbstractEloquentFilter
{
    public function __construct($distance, Coordinates $fromCoordinates)
    {
        $this->distance = $distance;
        $this->fromCoordinates = $fromCoordinates;
    }

    public function isApplicable(): bool
    {
        return $this->distance && is_numeric($this->distance);
    }

    public function apply(Builder $query): Builder
    {
        // your code
    }
}

Of course you may take another approach where you are in control of what's being passed into the filter parameters, instead of just blindly passing in the request payload. You could leverage DTO and type-hinting for that and have Filters collection factories to properly build a collection of filters. For instance

class ProductsController
{
    public function index(IndexProductsRequest $request)
    {
        $products = Product::filter(FiltersFactory::fromIndexProductsRequest($request))->get();

        return response()->json(['data' => $products]);
    }
}

Testing

composer test

Changelog

Please see CHANGELOG for more information on what has changed recently.

Contributing

Please see CONTRIBUTING for details.

Security Vulnerabilities

Please review our security policy on how to report security vulnerabilities.

Credits

License

The MIT License (MIT). Please see License File for more information.

atldays/laravel-eloquent-filters 适用场景与选型建议

atldays/laravel-eloquent-filters 是一款 基于 PHP 开发的 Composer 扩展包,目前已累计 52 次下载、GitHub Stars 达 0, 最近一次更新时间为 2026 年 04 月 10 日, 在 PHP 生态内属于活跃度较高的组件。

它主要适用于以下技术方向: 「laravel」 「eloquent-filters」 「laravel-eloquent-filters」 「model-filters」 「atldays」 等业务场景。在实际项目中,围绕这些方向常见需要落地的问题包括:接口对接、性能调优、并发安全、与既有框架(Laravel / ThinkPHP / Yii / Webman 等)的兼容适配,以及生产环境的日志埋点与稳定性保障。

我们在过去多个企业项目中使用过 atldays/laravel-eloquent-filters 或与其功能相近的方案,如果你在选型或落地过程中遇到问题,例如 版本兼容、二次改造、私有化封装、与内部系统对接、生产 BUG 排查,欢迎联系我们协助评估。

围绕 atldays/laravel-eloquent-filters 我们能提供哪些服务?
定制开发 / 二次开发

基于 atldays/laravel-eloquent-filters 在你已有业务上做功能扩展、字段裁剪、UI 适配、与内部账号 / 权限 / 日志系统的深度对接。

BUG 修复 & 性能优化

线上偶发问题、内存泄漏、慢查询、并发异常等排查修复;针对高流量场景做缓存、队列、索引层面的调优。

项目外包 & 长期维护

承接完整的项目从需求 → 设计 → 开发 → 上线 → 长期运维;也可按月提供技术保姆服务。

yvsm@zunyunkeji.com QQ:316430983 微信:yvsm316 西安尊云信息科技 · 专注 PHP / Go / 分布式系统研发

统计信息

  • 总下载量: 52
  • 月度下载量: 0
  • 日度下载量: 0
  • 收藏数: 0
  • 点击次数: 29
  • 依赖项目数: 1
  • 推荐数: 0

GitHub 信息

  • Stars: 0
  • Watchers: 0
  • Forks: 13
  • 开发语言: PHP

其他信息

  • 授权协议: MIT
  • 更新时间: 2026-04-10