ysm/filterable
Composer 安装命令:
composer require ysm/filterable
包简介
Laravel Filterable Package for Eloquent Models
README 文档
README
The YSM\Filterable package provides a flexible and reusable way to filter Eloquent queries in Laravel applications. It
allows developers to apply dynamic query filters based on HTTP request parameters, with support for whitelisting,
blacklisting, aliases, and default values. This package is designed to keep filtering logic separate from controllers
and models, promoting clean code and adherence to the Single Responsibility Principle.
Table of Contents
Installation
-
Install the Package via Composer: Install the
YSM\Filterablepackage using Composer:composer require ysm/filterable
-
Publish Configuration (Optional): If the package includes a configuration file, publish it to customize settings:
php artisan vendor:publish --provider="YSM\Filterable\FilterableServiceProvider"Note: If no service provider exists, you can skip this step as the package is ready to use after installation.
-
Requirements:
- PHP 8.0 or higher
- Laravel 8.x or higher
Configuration
The YSM\Filterable package does not require additional configuration out of the box. It integrates seamlessly with
Laravel's Eloquent ORM and HTTP request handling. To use it, you need to:
- Create a filter class that extends
YSM\Filterable\Filterable. - Apply the
InteractWithFilterabletrait to your Eloquent models.
Usage
Basic Usage
The package provides an abstract Filterable class and a trait InteractWithFilterable to apply filters to Eloquent
queries.
Step 1: Add the Trait to Your Model
Add the InteractWithFilterable trait to your Eloquent model:
<?php namespace App\Models; use Illuminate\Database\Eloquent\Model; use YSM\Filterable\Concerns\InteractWithFilterable; class Post extends Model { use InteractWithFilterable; protected $fillable = ['title', 'category', 'published', 'created_at']; }
This adds a filterable scope to the Post model, allowing you to apply filters using either a Filterable instance or a filter class name as a string.
Step 2: Create a Filter Class
Create a filter class that extends YSM\Filterable\Filterable:
<?php namespace App\Http\Filters; use YSM\Filterable\Filterable; use Illuminate\Database\Eloquent\Builder; class PostFilter extends Filterable { protected array $allowedFilters = ['title', 'category', 'published']; public function title(string $value): void { $this->builder->where('title', 'like', "%{$value}%"); } public function category(string $value): void { $this->builder->where('category', $value); } public function published(bool $value): void { $this->builder->where('published', $value); } }
Step 3: Use in a Controller
Apply the filter in a controller. You can use the filter in two ways:
Method 1: Using Filter Instance
<?php namespace App\Http\Controllers; use App\Http\Filters\PostFilter; use App\Models\Post; class PostController extends Controller { public function index() { $filter = PostFilter::make(); $posts = Post::filterable($filter)->get(); return response()->json(['data' => $posts]); } }
Method 2: Using Filter Class Name (String)
<?php namespace App\Http\Controllers; use App\Http\Filters\PostFilter; use App\Models\Post; class PostController extends Controller { public function index() { // Pass the filter class name as a string $posts = Post::filterable(PostFilter::class)->get(); return response()->json(['data' => $posts]); } }
Note: When using a string class name, the filterable method will automatically resolve the filter from Laravel's service container and validate that it implements the
Filterableinterface.
When to Use Each Method:
- Filter Instance: Use when you need to add additional configuration to the filter instance (aliases, defaults, etc.) or override existing behavior before applying it.
- String Class Name: Use for simple and direct applying the filter without needing to add additional configuration.
Example Request:
curl -X GET "http://your-app.test/posts?title=Test&category=news&published=1" \ -H "Accept: application/json"
Response:
{
"data": [
{
"id": 1,
"title": "Test Post",
"category": "news",
"published": true,
"created_at": "2025-01-01T00:00:00.000000Z"
}
]
}
Advanced Use Cases
Using Aliases
Map request parameters to filter methods using the aliases method:
<?php namespace App\Http\Filters; use YSM\Filterable\Filterable; use Illuminate\Database\Eloquent\Builder; class PostFilter extends Filterable { protected array $allowedFilters = ['title', 'category', 'published']; protected array $aliases = [ 'cat' => 'category', // Maps 'cat' request param to 'category' filter ]; public function title(string $value): void { $this->builder->where('title', 'like', "%{$value}%"); } public function category(string $value): void { $this->builder->where('category', $value); } public function published(bool $value): void { $this->builder->where('published', $value); } }
Controller:
$filter = PostFilter::make()->aliases(['cat' => 'category']); $posts = Post::filterable($filter)->get();
Request:
curl -X GET "http://your-app.test/posts?cat=news"
This applies the category filter using the cat request parameter.
Auto-Applying Filters
Automatically apply filters without requiring request parameters:
<?php namespace App\Http\Filters; use YSM\Filterable\Filterable; use Illuminate\Database\Eloquent\Builder; class PostFilter extends Filterable { protected array $autoApplyFilters = ['published']; public function published(bool $value = true): void { $this->builder->where('published', $value); } }
Controller:
$filter = PostFilter::make()->autoApply(['published']); $posts = Post::filterable($filter)->get();
This ensures all queries return only published posts unless overridden.
Whitelisting and Blacklisting Filters
Restrict which filters can or cannot be applied:
<?php namespace App\Http\Filters; use YSM\Filterable\Filterable; use Illuminate\Database\Eloquent\Builder; class PostFilter extends Filterable { protected array $allowedFilters = ['title', 'category']; // Whitelist protected array $forbiddenFilters = ['created_at']; // Blacklist public function title(string $value): void { $this->builder->where('title', 'like', "%{$value}%"); } public function category(string $value): void { $this->builder->where('category', $value); } public function created_at(string $value): void { $this->builder->whereDate('created_at', $value); } }
Controller:
$filter = PostFilter::make()->only(['title', 'category'])->except(['created_at']); $posts = Post::filterable($filter)->get();
Request:
curl -X GET "http://your-app.test/posts?title=Test&created_at=2025-01-01"
The created_at filter will be ignored due to the blacklist.
Setting Default Filter Values
Provide default values for filters:
<?php namespace App\Http\Filters; use YSM\Filterable\Filterable; use Illuminate\Database\Eloquent\Builder; class PostFilter extends Filterable { protected array $defaults = ['published' => true, 'category' => 'blog']; public function category(string $value): void { $this->builder->where('category', $value); } public function published(bool $value): void { $this->builder->where('published', $value); } }
Controller:
$filter = PostFilter::make()->defaults(['published' => true, 'category' => 'blog']); $posts = Post::filterable($filter)->get();
Request:
curl -X GET "http://your-app.test/posts"
This returns only published blog posts if no parameters are provided.
Debugging Applied Filters
Retrieve applied filters for debugging:
<?php namespace App\Http\Controllers; use App\Http\Filters\PostFilter; use App\Models\Post; class PostController extends Controller { public function index() { $filter = PostFilter::make()->only(['title', 'category']); $posts = Post::filterable($filter)->get(); return response()->json([ 'data' => $posts, 'applied_filters' => $filter->getAppliedFilters(), 'configured_filters' => $filter->getConfiguredFilters(), ]); } }
Response:
{
"data": [
{
"id": 1,
"title": "Test Post",
"category": "news",
"published": true,
"created_at": "2025-01-01T00:00:00.000000Z"
}
],
"applied_filters": {
"title": "Test",
"category": "news"
},
"configured_filters": {
"autoApply": [],
"aliases": [],
"allowed": ["title", "category"],
"forbidden": [],
"defaults": []
}
}
Contributing
Contributions are welcome! Please submit pull requests or issues to the GitHub repository. Ensure your code follows PSR-12 standards.
License
This package is open-sourced under the MIT License.
ysm/filterable 适用场景与选型建议
ysm/filterable 是一款 基于 PHP 开发的 Composer 扩展包,目前已累计 1.19k 次下载、GitHub Stars 达 8, 最近一次更新时间为 2025 年 07 月 06 日, 在 PHP 生态内属于活跃度较高的组件。
它主要适用于以下技术方向: 「query」 「model」 「filterable」 「laravel」 「eloquent」 等业务场景。在实际项目中,围绕这些方向常见需要落地的问题包括:接口对接、性能调优、并发安全、与既有框架(Laravel / ThinkPHP / Yii / Webman 等)的兼容适配,以及生产环境的日志埋点与稳定性保障。
我们在过去多个企业项目中使用过 ysm/filterable 或与其功能相近的方案,如果你在选型或落地过程中遇到问题,例如 版本兼容、二次改造、私有化封装、与内部系统对接、生产 BUG 排查,欢迎联系我们协助评估。
基于 ysm/filterable 在你已有业务上做功能扩展、字段裁剪、UI 适配、与内部账号 / 权限 / 日志系统的深度对接。
线上偶发问题、内存泄漏、慢查询、并发异常等排查修复;针对高流量场景做缓存、队列、索引层面的调优。
承接完整的项目从需求 → 设计 → 开发 → 上线 → 长期运维;也可按月提供技术保姆服务。
与 ysm/filterable 相关的其它包
同方向 / 同关键字的高下载量 PHP Composer 包推荐,方便对比选型:
A package for automatically encrypting and decrypting Eloquent attributes in Laravel 5.5+, based on configuration settings.
Doctrine2 behavior traits - slowhop fork
Query filtering in your frontend
Interfaces for web resource models and services to retrieve and create them
Anax Database Active Record module for model classes.
Doctrine2 behavior traits
统计信息
- 总下载量: 1.19k
- 月度下载量: 0
- 日度下载量: 0
- 收藏数: 8
- 点击次数: 3
- 依赖项目数: 0
- 推荐数: 0
其他信息
- 授权协议: MIT
- 更新时间: 2025-07-06