定制 laraditz/model-filter 二次开发

按需修改功能、优化性能、对接业务系统,提供一站式技术支持

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

laraditz/model-filter

Composer 安装命令:

composer require laraditz/model-filter

包简介

A simple eloquent model filter.

README 文档

README

Latest Stable Version Total Downloads License

A flexible Eloquent model filter for Laravel with operator support, OR grouping, and relationship filtering.

v2 breaking change: Filter params are now namespaced under filters[]. See the breaking changes section below.

Requirements

  • PHP 8.1+
  • Laravel 9 - 13

Installation

composer require laraditz/model-filter

Setup

Add the Filterable trait to your model and declare a $filterable allowlist:

use Laraditz\ModelFilter\Filterable;

class User extends Model
{
    use Filterable;

    protected array $filterable = [
        'name',
        'email',
        'age',
        'role.name',  // dot-notation opts in to relationship filtering
    ];

    public function role(): BelongsTo
    {
        return $this->belongsTo(Role::class);
    }
}

Optionally scaffold a filter class with the Artisan command:

php artisan make:filter UserFilter

This creates app/Filters/UserFilter.php. Use --force to overwrite an existing file.

Then add your custom methods:

namespace App\Filters;

use Laraditz\ModelFilter\Filter;

class UserFilter extends Filter
{
    public function name(mixed $value): void
    {
        $this->query->where('name', 'LIKE', $value . '%');
    }
}

Fields without a custom method are handled automatically.

Custom method precedence: When a custom method exists for a field, it always takes precedence over auto-handling — and it receives only the value, not the operator. This means ?filters[age][gte]=18 will call age('18') and silently drop the gte operator. If you need operator-based filtering for a field, do not define a custom method for it and let auto-handling do the work.

Usage

Pass $request->all() to filter():

$users = User::filter($request->all())->get();

Query param format

# Shorthand (defaults to eq)
?filters[name]=farhan

# Explicit operator
?filters[age][gte]=18

# Multiple filters - all AND'd together
?filters[status]=active&filters[age][gte]=18

# Multiple operators on same field
?filters[age][gte]=18&filters[age][lte]=65

# OR group - produces: AND (name LIKE '%far%' OR email LIKE '%far%')
?filters[or][name][like]=far&filters[or][email][like]=far

# Relationship filtering
?filters[role.name][eq]=admin

# Sort - top-level, not inside filters[]
?sort=name,-created_at

Supported operators

Operator SQL equivalent Notes
eq = ? Default when no operator bracket used
neq != ?
like LIKE ? Value wrapped in %…% automatically
gt > ?
gte >= ?
lt < ?
lte <= ?
in IN (?) Comma-separated string → array
between BETWEEN ? AND ? Comma-separated, exactly 2 values

Relationship filtering

Add the relationship column in dot-notation to $filterable:

protected array $filterable = [
    'name',
    'role.name',   // enables ?filters[role.name][...]=...
];

The package translates role.name into a whereHas('role', ...) clause automatically. All operators work:

# Users whose role name equals "admin"
?filters[role.name][eq]=admin

# Users whose role name contains "mod"
?filters[role.name][like]=mod

# Combined with a direct field filter
?filters[name][like]=john&filters[role.name][eq]=admin

Only one level of nesting is supported (relation.column). Deeper nesting (e.g. post.comments.body) is not supported.

Custom relationship query

If you need more control — for example filtering on a condition that spans multiple columns of the related model — define a custom method in your filter class:

class UserFilter extends Filter
{
    /**
     * ?filters[active_admin]=1
     * Finds users with an active role named "admin".
     */
    public function activeAdmin(mixed $value): void
    {
        if (! $value) {
            return;
        }

        $this->query->whereHas('role', function ($q): void {
            $q->where('name', 'admin')
              ->where('active', true);
        });
    }
}

Remember to add the key to $filterable:

protected array $filterable = ['active_admin'];

Security

Only fields listed in $filterable can be filtered. Unlisted fields are silently ignored. Values are bound via PDO prepared statements - no SQL injection risk.

Breaking Changes from v1

Area v1 v2
Query params ?name=farhan ?filters[name]=farhan
Laravel support 7–12 9–13
PHP minimum 7.4 8.1
Lumen Supported Dropped
$filterable empty All params passed through All filtering disabled
Filter::__call__ Auto-proxied to Builder Removed — use $this->query directly
Filter::sort() On Filter base class Moved to Filterable trait

Credits

License

MIT. Please see the license file for more information.

laraditz/model-filter 适用场景与选型建议

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

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

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

围绕 laraditz/model-filter 我们能提供哪些服务?
定制开发 / 二次开发

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

BUG 修复 & 性能优化

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

项目外包 & 长期维护

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

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

统计信息

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

GitHub 信息

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

其他信息

  • 授权协议: MIT
  • 更新时间: 2021-04-01