Advanced Eloquent Query Filtering with Filterable

最后更新于 经过

Advanced Eloquent Query Filtering with Filterable image

可过滤 , by Abdalrhman Emad Saad , is a Laravel package that provides a structured approach to Eloquent query filtering. Instead of manual query building in controllers, it uses dedicated filter classes and multiple specialized engines to map HTTP requests to database queries.

The package's core strength lies in its modular engine architecture, allowing developers to choose the filtering style that best fits their frontend requirements.

基本用法

To get started, add the HasFilterable trait to your model and optionally bind a default filter class:

命名空间 应用程序\模型 ;
使用 App\Http\Filters\TaskFilter ;
使用 Kettasoft\Filterable\Traits\HasFilterable ;
使用 照亮\数据库\雄辩\模型 ;
班级 任务 延伸 模型
{
使用 HasFilterable ;
受保护 $filterable = TaskFilter ::班级 ;
}

Now, you can apply filters directly in your controller. The package automatically detects the request parameters:

民众 功能 指数 ()
{
// Uses the bound TaskFilter automatically
返回 任务 :: 筛选 () -> 分页 ();
}

Multiple Filtering Engines

Filterable includes four built-in engines that handle different request formats:

  • Invokable Engine: Maps request keys to specific methods in your filter class. It supports PHP 8 annotations for casting, validation, and authorization.
  • Ruleset Engine: Handles flat field-operator-value queries for resource lists, such as finding high-stock inventory items (e.g., ?filter[stock][gte]=500&filter[category]=electronics )。
  • Expression Engine: Extends the Ruleset engine to support deep Eloquent relationship filtering using dot notation, such as filtering support tickets by the customer's plan level (e.g., ?filter[user.subscription.plan][eq]=premium )。
  • Tree Engine: Processes nested AND/OR JSON trees, recursively translating them into Eloquent whereorWhere groups.

PHP 8 Annotations for Filter Logic

The Invokable engine utilizes PHP 8 attributes to handle common tasks like input sanitization and validation directly on the filter methods. This allows you to define constraints like required fields or role-based access at the method level:

班级 TaskFilter 延伸 可过滤
{
受保护 $filters = [ '标题' , '优先事项' , '到期日' ];
受保护 功能 标题 Payload $payload)
{
// Use asLike() for automatic wildcard wrapping
返回 $this -> 建造者 -> 在哪里 '标题' , '喜欢' , $payload -> asLike 'both' ));
}
#[ Cast ‘整数’ )]
#[ ([ 1 , 2 , 3 ])]
受保护 功能 优先事项 Payload $payload)
{
返回 $this -> 建造者 -> 在哪里 'priority_level' , $payload -> 价值);
}
#[ 授权 'manage-tasks' )]
#[ 必需的 ]
#[ 日期 ]
受保护 功能 due_date Payload $payload)
{
返回 $this -> 建造者 -> whereDate 'deadline' , '<=' , $payload -> 价值);
}
}

Built-in Caching System

The package features an integrated caching system designed specifically for the filter pipeline. It supports tagging, conditional caching, and scoping by user or tenant:

// Cache store inventory for 30 minutes, isolated by branch ID
产品 :: 筛选 () -> 缓存 1800 -> scopeByTenant ($branchId) -> 得到 ();
// Only cache results for guest users to reduce load on public listings
列表 :: 筛选 () -> cacheWhen 授權 () -> 客人 (), 3600 -> cacheTags ([ 'public_listings' ]) -> 得到 ();

Filterable also includes an auto-invalidation feature that can be configured to clear specific cache tags when models are created, updated, or deleted.

CLI and Debugging Tools

Filterable provides several Artisan commands to assist with development and debugging:

  • php artisan filterable:setup : Initial configuration and environment setup.
  • php artisan filterable:make-filter : Generate a new filter class scaffold.
  • php artisan filterable:test : Test a filter class with sample data strings (e.g., --data="status=active" )。
  • php artisan filterable:inspect : View details about a filter class, including its engines and validation rules.
  • php artisan filterable:discover : Automatically register filter classes within the application.

安装

您可以通过 Composer 安装该软件包:

作曲家 要求 kettasoft/filterable

The package requires PHP 8.1 or higher and supports Laravel 10 through 12 as of this writing. For more information, you can visit the Filterable documentation or view the source code on GitHub

Yannick Lyn Fatt 的照片

Laravel News 的特约撰稿人和全栈 Web 开发人员。

归档于:
立方体

Laravel 时事通讯

加入超过 4 万名开发者的行列,不错过任何新的技巧、教程等内容。

图像
了解软科技

以每小时 20 美元的价格聘请具备人工智能专业知识的 Laravel 开发人员。48 小时内即可开始工作。

访问 Acquaint Softtech
了解 Softtech 的标志

了解软科技

Acquaint Softtech 提供 AI 就绪的 Laravel 开发人员,48 小时内即可上手,每月费用为 3000 美元,没有冗长的销售流程,并提供 100% 退款保证。

了解软科技
鱼叉:新一代时间跟踪和发票标志

Harpoon:新一代时间跟踪和发票系统

新一代时间跟踪和计费软件,帮助您的机构规划和预测盈利的未来。

Harpoon:新一代时间跟踪和发票系统
Lucky Media 标志

幸运传媒

Get Lucky Now——拥有十余年经验的 Laravel 开发理想之选!

幸运传媒
SaaSykit:Laravel SaaS 入门套件徽标

SaaSykit:Laravel SaaS 入门套件

SaaSykit 是一个多租户 Laravel SaaS 入门套件,包含运行现代 SaaS 所需的所有功能,例如支付、美观的结账界面、管理面板、用户仪表盘、身份验证、现成组件、统计数据、博客、文档等等。

SaaSykit:Laravel SaaS 入门套件
Laravel Cloud 标志

Laravel 云

轻松创建和管理服务器,并在几秒钟内部署 Laravel 应用程序。

Laravel 云
Shift 标志

转移

还在运行旧版本的 Laravel?立即实现 Laravel 自动升级和代码现代化,让您的应用程序保持最新状态。

转移
Tinkerwell 徽标

廷克威尔

Laravel 开发者必备的代码运行器。可在本地和生产环境中体验 AI、自动补全和即时反馈功能。

廷克威尔
PhpStorm 标志

PhpStorm

首选的 PHP IDE,对 Laravel 及其生态系统提供广泛的开箱即用支持。

PhpStorm
绝不妥协标志

绝不妥协

来自 No Compromises 播客的两位经验丰富的开发者 Joel 和 Aaron 现在可以为您的 Laravel 项目提供服务。⬧ 固定费用 9500 美元/月。⬧ 无冗长的销售流程。⬧ 无需签订合同。⬧ 100% 退款保证。

绝不妥协
Kirschbaum 标志

樱桃树

提供创新和稳定性,确保您的Web应用程序取得成功。

樱桃树
Scheduler List: A Web Dashboard for Laravel's Scheduled Tasks image

Scheduler List: A Web Dashboard for Laravel's Scheduled Tasks

阅读文章
Community Laravel Extension for Zed image

Community Laravel Extension for Zed

阅读文章
Bulk Job Dispatching with Bus::bulk() in Laravel 13.13 image

Bulk Job Dispatching with Bus::bulk() in Laravel 13.13

阅读文章
Audit Laravel Apps for Security Issues with Checkpoint image

Audit Laravel Apps for Security Issues with Checkpoint

阅读文章
In-Memory Eloquent Models with Truffle image

In-Memory Eloquent Models with Truffle

阅读文章
Detect and Resolve Laravel Schema Drift with MigrAlign image

Detect and Resolve Laravel Schema Drift with MigrAlign

阅读文章