freebuu/laravel-filterable
Composer 安装命令:
composer require freebuu/laravel-filterable
包简介
Model filters for your index requests
README 文档
README
Simple filter and paginate index data. Main idea - KISS.
Example query:
?search_description=some%20text&sort_id=desc&where_publisher_id=1,23&where_has_groups__id=30,40&limit=10&offset=20
In code this query reflects:
- search_description=some%20text -
$builder->where('description', 'like', '%some%text%') - sort_id=desc -
$builder->sortBy('id', 'desc') - where_publisher_id=1,23 -
$builder->whereIn('publisher_id', [1,23]) - where_has_groups__id=30,40 -
$builder->whereHas('groups', fn($builder) => $builder->whereIn('id', [30,40])) - limit=10 -
$builder->limit(10) - offset=20 -
$builder->offset(20)
Installation
Requires laravel >= 9 and php ^8.1
composer require freebuu/laravel-filterable
Basic usage (pagination only)
Add HasRequestFilter trait to Model - that's all.
class PostIndexController { public function __invoke(Request $request): JsonResponse { return Post::requestFilter()->jsonResponse(PostResource::class) } }
Example result for query /api/posts/?limit=25&offset=10
{
"meta": {
"limit": 25,
"offset": 10,
"total": 2
},
"data": [
{
"id": "1",
"title": "post title"
},
{
"id": "2",
"title": "another post title"
}
]
}
meta- object with pagination datadata- array with model data, wrapped inPostResource
Filtration
For filtration, you need to create a filter class for each model. Filter class must extend AbstractFilter. Best place for these classes is App\Http\Filters.
In method getFilterableFields() you specify which fields can be filtered in each filter case.
HINT - always add default state because filter cases may be supplemented.
class PostFilter extends AbstractFilter { protected function getFilterableFields(FilterCaseEnum $case): array { return match ($case) { FilterCaseEnum::WHERE => ['publisher_id'], FilterCaseEnum::SORT => ['id'], FilterCaseEnum::WHERE_HAS => ['groups' => ['id']] default => [] }; } }
To set this filter for Model - add property requestFilter
class Post extends Model { use HasRequestFilter; protected string $requestFilter = PostFilter::class; }
Filter case
Filterable query params contains four parts separated with _. Let's see example with where_has_groups__id=30,40
- $case - where_has
- $field - groups
- $fieldValue - id (optional, mandatory only with where_has)
- $value - 30,40
In code, they are presented as FilterCaseEnum.php and they work like this
- FROM
- Accepts only int
$builder->where($field, '>=', $value)
- TO
- Accepts only int
$builder->where($field, '<=', $value)-
- SORT - sorting
- Accepts only
asc,desc $builder->sortBy($field, $value)
- Accepts only
- SEARCH - search with
likeoperator- Accept string with spaces. Add
%at start, end and instead of all spaces $builder->where($field', 'like', $value)
- Accept string with spaces. Add
- START_WITH - all strings starts with passed value
- Accept string without spaces. Add
%at end of value $builder->where($field', 'like', $value)
- Accept string without spaces. Add
- WHERE_HAS - filter by relation with array of values
- Accept comma separated array of values.
- For this filter
fieldValuefields must be set (see in example inPostFilter) $builder->whereHas($field, fn($builder) => $builder->whereIn($fieldValue, $value))
- WHERE - filter by array of values
- Accept comma separated array of values.
$builder->whereIn($fieldValue, $value)
- FILTER - uses for custom filters, see below
Custom filters
In filter class you can make custom filter by creating a method like filterCustom - it must begin with filter. Then yoy can use it in query like ?filter_custom=123
HINT - you can use fieldValue here like ?filter_custom__alias=123 - it pass as third parameter in filter method.
class PostFilter extends AbstractFilter { public function filterCustom(Builder $builder, mixed $value, mixed $fieldValue): void { //you have request instance here if($this->request->query('something')){ return; } //$value will be 123 //$fieldValue will be alias (or can be null) $builder->where('some_field', $value)->where($fieldValue, '432') } }
Advanced usage
Limit
For security reasons, the limit field is set to a maximum value. If the request specifies a value greater, it will be reset to the default value.
- Default it set to
30 - You can override this value in Filter class - overwrite the
maxLimitproperty. - Or you can override it system-wide in
AppServiceProvider
class AppServiceProvider extends ServiceProvider { public function register() { AbstractFilter::$defaultMaxLimit = 50; } }
Query callbacks
Sometimes you need to set up query condition situational—e.g. filter only for auth user
Post::requestFilter() ->addQueryCallback(fn (Builder $builder) => $builder->where('author_id', auth()->id())) ->response(ResourceClass::class);
Or just use Builder mixin:
Post::requestFilter() ->where('author_id', auth()->id()) ->response(ResourceClass::class);
freebuu/laravel-filterable 适用场景与选型建议
freebuu/laravel-filterable 是一款 基于 PHP 开发的 Composer 扩展包,目前已累计 119 次下载、GitHub Stars 达 0, 最近一次更新时间为 2024 年 04 月 24 日, 在 PHP 生态内属于活跃度较高的组件。
它主要适用于以下技术方向: 「laravel」 「request filter」 「laravel filter」 「laravel filterable」 等业务场景。在实际项目中,围绕这些方向常见需要落地的问题包括:接口对接、性能调优、并发安全、与既有框架(Laravel / ThinkPHP / Yii / Webman 等)的兼容适配,以及生产环境的日志埋点与稳定性保障。
我们在过去多个企业项目中使用过 freebuu/laravel-filterable 或与其功能相近的方案,如果你在选型或落地过程中遇到问题,例如 版本兼容、二次改造、私有化封装、与内部系统对接、生产 BUG 排查,欢迎联系我们协助评估。
基于 freebuu/laravel-filterable 在你已有业务上做功能扩展、字段裁剪、UI 适配、与内部账号 / 权限 / 日志系统的深度对接。
线上偶发问题、内存泄漏、慢查询、并发异常等排查修复;针对高流量场景做缓存、队列、索引层面的调优。
承接完整的项目从需求 → 设计 → 开发 → 上线 → 长期运维;也可按月提供技术保姆服务。
与 freebuu/laravel-filterable 相关的其它包
同方向 / 同关键字的高下载量 PHP Composer 包推荐,方便对比选型:
Nova searchable filter for belongsTo relationships.
Symfony DataGridBundle
HTTP request logger middleware for Laravel
Adds request-parameter validation to the SLIM 3.x PHP framework
Data provider for yii2
This Laravel Nova package allows you to detach filters from the filter dropdown
统计信息
- 总下载量: 119
- 月度下载量: 0
- 日度下载量: 0
- 收藏数: 0
- 点击次数: 20
- 依赖项目数: 0
- 推荐数: 0
其他信息
- 授权协议: MIT
- 更新时间: 2024-04-24