freebuu/laravel-filterable 问题修复 & 功能扩展

解决BUG、新增功能、兼容多环境部署,快速响应你的开发需求

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

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 data
  • data - array with model data, wrapped in PostResource

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)
  • SEARCH - search with like operator
    • Accept string with spaces. Add % at start, end and instead of all spaces
    • $builder->where($field', 'like', $value)
  • START_WITH - all strings starts with passed value
    • Accept string without spaces. Add % at end of value
    • $builder->where($field', 'like', $value)
  • WHERE_HAS - filter by relation with array of values
    • Accept comma separated array of values.
    • For this filter fieldValue fields must be set (see in example in PostFilter)
    • $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 maxLimit property.
  • 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 我们能提供哪些服务?
定制开发 / 二次开发

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

BUG 修复 & 性能优化

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

项目外包 & 长期维护

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

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

统计信息

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

GitHub 信息

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

其他信息

  • 授权协议: MIT
  • 更新时间: 2024-04-24