Weave Code
Weaver
Helps Laravel developers discover, compare, and choose open-source packages. See popularity, security, maintainers, and scores at a glance to make better decisions.
Feedback
Share your thoughts, report bugs, or suggest improvements.
Subject
Message

Model Filter Laravel Package

laraditz/model-filter

Flexible Eloquent model filtering for Laravel with operator support (eq, gte, etc.), AND/OR grouping, and relationship filters via dot notation. Add a Filterable trait and allowlist fields, optionally create filter classes for custom logic, and filter using request params under filters[].

View on GitHub
Deep Wiki
Context7

Technical Evaluation

Architecture Fit

  • Eloquent Integration: The package leverages Laravel’s Eloquent ORM, making it a natural fit for applications already using Eloquent models. It extends query building without requiring a full rewrite of existing logic.
  • Flexibility: Supports basic field filtering, operator-based queries (e.g., =, >, <), and relationship filtering via dot notation (e.g., role.name). This aligns well with common API filtering needs.
  • API-First Design: The filters[] namespace (post-v2) suggests it’s optimized for API use cases where query parameters are passed as an array (e.g., ?filters[name]=John&filters[age]>30).

Integration Feasibility

  • Low Coupling: The Filterable trait is additive, requiring minimal changes to existing models. No core Laravel files are modified.
  • Artisan Scaffold: The make:filter command provides a structured way to define custom filter logic, reducing boilerplate.
  • Lumen Support: Works in Lumen, expanding use cases to lightweight APIs.

Technical Risk

  • Breaking Changes: v2’s filters[] namespace shift could disrupt existing implementations if not accounted for during migration.
  • Performance: Complex nested filters (e.g., deep relationships) may introduce N+1 query risks if not optimized with with() or eager loading.
  • Validation: No built-in request validation for filter inputs; developers must implement this separately (e.g., via Laravel’s Validator or API resources).
  • Testing: Lack of stars/downloads suggests unproven scalability; stress-testing with large datasets is recommended.

Key Questions

  1. Use Case Alignment: Does the application heavily rely on dynamic, API-driven filtering? If not, the package may add unnecessary complexity.
  2. Operator Support: Are all required operators (e.g., LIKE, IN, NULL) supported out-of-the-box, or will custom methods be needed?
  3. Relationship Depth: How deep are the relationships being filtered? Deeply nested filters may require manual query optimization.
  4. Authentication/Authorization: How will filter access be controlled (e.g., restricting admin fields to admins only)?
  5. Legacy Code: Are there existing query builders or scopes that would conflict with this package?

Integration Approach

Stack Fit

  • PHP/Laravel: Native support for PHP 8.1+ and Laravel 9–13 ensures compatibility with modern stacks.
  • APIs: Ideal for REST/GraphQL APIs where client-driven filtering is required (e.g., admin dashboards, public search endpoints).
  • Microservices: Lumen compatibility enables lightweight integration in service-oriented architectures.

Migration Path

  1. Assessment Phase:
    • Audit existing query logic (e.g., manual where clauses, scopes) to identify candidates for replacement.
    • Validate if current filter inputs align with the filters[] namespace (v2 requirement).
  2. Pilot Implementation:
    • Start with a single model (e.g., User) to test the trait and scaffolded filter class.
    • Compare performance of filtered queries vs. existing implementations.
  3. Gradual Rollout:
    • Replace manual filtering logic incrementally, prioritizing high-impact endpoints.
    • Use feature flags to toggle between old and new filter logic during transition.
  4. Customization:
    • Extend the scaffolded UserFilter class with model-specific logic (e.g., scopeActive()).
    • Implement request validation for filter inputs (e.g., using Laravel’s FormRequest or API resources).

Compatibility

  • Laravel Versions: Confirmed compatibility with 9–13; test thoroughly if using older versions.
  • Database Drivers: No driver-specific limitations, but complex filters may behave differently across SQL dialects (e.g., PostgreSQL vs. MySQL).
  • Third-Party Packages: Potential conflicts with packages that modify Eloquent queries (e.g., spatie/laravel-query-builder). Test in isolation.

Sequencing

  1. Setup:
    • Install via Composer and add the trait to target models.
    • Scaffold filter classes for critical models.
  2. Core Integration:
    • Replace manual where clauses with filter trait usage in controllers/services.
    • Update API routes to accept filters[] input.
  3. Optimization:
    • Add eager loading (with()) for relationships to mitigate N+1 queries.
    • Implement caching for frequent filter combinations (e.g., Redis).
  4. Validation:
    • Add request validation for filter inputs (e.g., filters[age] must be numeric).
  5. Monitoring:
    • Log filter usage to identify performance bottlenecks or unusual queries.

Operational Impact

Maintenance

  • Pros:
    • Centralized Logic: Filter rules are defined in scaffolded classes (e.g., UserFilter), making them easier to maintain than scattered where clauses.
    • Consistent API: Enforces a standardized way to handle filtering across the codebase.
  • Cons:
    • Trait Bloat: Adding the trait to every model may feel redundant for simple projects.
    • Dependency Risk: Relies on a third-party package with minimal community adoption; updates may introduce breaking changes.

Support

  • Debugging:
    • Filter queries can be complex to debug due to dynamic input. Log raw filter arrays and generated SQL for troubleshooting.
    • Lack of documentation/examples may require reverse-engineering the package’s internals.
  • Community:
    • Limited stars/downloads suggest minimal community support; issues may go unanswered.
    • MIT license allows forks/modifications if needed.

Scaling

  • Performance:
    • Pros: Reduces boilerplate, making it easier to add filters to high-traffic endpoints.
    • Cons: Poorly optimized filters (e.g., no indexes on filtered columns) can degrade performance. Monitor query execution plans.
  • Database Load:
    • Complex filters may generate heavy queries. Consider:
      • Database indexing for frequently filtered columns.
      • Query caching for static filter sets.
      • Rate-limiting for abusive filter inputs (e.g., filters[id][0]=1&filters[id][1]=2&...).
  • Horizontal Scaling:
    • Stateless design (filters are request-dependent) works well with queued jobs or read replicas.

Failure Modes

  1. SQL Injection:
    • Risk: Dynamic filter inputs could expose SQL injection if not sanitized.
    • Mitigation: Use Laravel’s query builder (which this package does) and validate inputs strictly.
  2. Resource Exhaustion:
    • Risk: Malicious or poorly designed filters (e.g., filters[created_at][0]=1970-01-01&filters[created_at][1]=2030-01-01) could return massive datasets.
    • Mitigation: Implement pagination (?page=1) and size limits (?limit=100) by default.
  3. Broken Queries:
    • Risk: Invalid filter inputs (e.g., filters[non_existent_field]=value) may throw errors or return incorrect results.
    • Mitigation: Validate filter keys against $filterable allowlist and handle unknown fields gracefully.
  4. Caching Issues:
    • Risk: Cached responses may stale if filters are dynamic (e.g., user-specific filters).
    • Mitigation: Use request-specific cache keys or avoid caching filtered queries.

Ramp-Up

  • Learning Curve:
    • Low: Basic usage (e.g., filters[name]=John) is intuitive. Custom methods require understanding of Eloquent scopes.
    • Documentation Gap: Lack of tutorials or real-world examples may slow adoption.
  • Onboarding:
    • Training: Pair developers with examples of existing filter implementations.
    • Documentation: Create internal docs for:
      • Common filter patterns (e.g., date ranges, relationship filters).
      • Debugging techniques (e.g., logging SQL).
      • Custom method signatures.
  • Tooling:
    • IDE Support: No specific plugins, but PHPStorm’s Laravel plugin can help navigate scaffolded filter classes.
    • Testing: Write feature tests for filter logic using Laravel’s HttpTests or TestCase. Example:
      public function test_user_filter_by_name()
      {
          $user = User::factory()->create(['name' => 'John']);
          $response = $this->get('/users', ['filters[name]' => 'John']);
          $response->assertJsonCount(1);
      }
      
Weaver

How can I help you explore Laravel packages today?

Conversation history is not saved when not logged in.
Prompt
Add packages to context
No packages found.
andydefer/laravel-notification
adachsoft/cli-process-tester
jhaskell13/laraflow
sebastienheyd/boilerplate-media-manager
ccast/tagixo-primix
pretendtrue/laravel-builder
sawmainek/laravel-scout-tntsearch-driver
tomshaw/laravel-calendar-table
dibakar/laravel-ownership
steadrun/laravel-monitor
labyrinthe/connect-laravel
elmogy/layan
drewdan/sentinel-client
dskripchenko/laravel-llm
fatryst/nuonuo
stevenay/myanfont
gmostafa/php-graphql-client
xeviant/paystack
snowsoft/faker
meditationsteps/blogetc