Weave Code
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

Eloquent Filtering Laravel Package

indexzer0/eloquent-filtering

Define allowed filters on your Eloquent models and apply them from simple arrays or request data—no custom query logic. Supports complex, type-based filtering for APIs and dashboards on Laravel 10+ / PHP 8.2+.

View on GitHub
Deep Wiki
Context7

Technical Evaluation

Architecture Fit

  • Pros:

    • Decouples filtering logic from business logic, adhering to Single Responsibility Principle (SRP) by encapsulating filter definitions within Eloquent models.
    • Leverages Laravel’s Eloquent natively, reducing friction for teams already using Laravel.
    • Supports complex queries (e.g., JSON fields, nested conditions) without manual SQL or custom query builders.
    • Type-safe filter definitions via FilterType enums, reducing runtime errors.
    • Extensible—custom filter types can be added via service providers or traits.
  • Cons:

    • Tight coupling to Eloquent: Not suitable for non-Eloquent query builders (e.g., raw PDO, Query Builder without models).
    • Filter definitions are model-specific, which may require duplication if similar models share filtering logic.
    • Sorting is experimental (per docs), introducing potential instability.

Integration Feasibility

  • Low-risk for greenfield projects: Designed for Laravel 10+, with minimal setup (composer install + artisan command).
  • Backward compatibility: Requires PHP 8.2+, which may necessitate PHP upgrades in legacy systems.
  • API/HTTP-first design: Optimized for filtering from HTTP requests (e.g., REST/GraphQL APIs), aligning with modern Laravel applications.
  • Database agnosticism: Uses Eloquent’s query builder, so it works with any supported database (MySQL, PostgreSQL, SQLite, etc.).

Technical Risk

  • Performance overhead:
    • Dynamic query building may introduce N+1 query risks if not paired with with() or load().
    • Complex JSON filters (e.g., $jsonLength) could impact query performance on large datasets.
  • Security risks:
    • SQL injection: Mitigated by Eloquent’s query builder, but improper use of raw values (e.g., user input in Filter::field()) could expose vulnerabilities.
    • Overly permissive filters: Default allowedFilters() must be carefully configured to avoid exposing sensitive fields.
  • Behavioral risks:
    • Unexpected filter precedence: Nested $or/$and conditions may not behave as expected without thorough testing.
    • Sorting instability: Experimental feature may break in minor updates.

Key Questions

  1. Does the target system heavily rely on non-Eloquent queries?
    • If yes, this package may not fit without significant refactoring.
  2. Are there existing custom filter implementations?
    • Migrating from ad-hoc filtering logic to this package may require rewrite effort.
  3. What’s the scale of filtered queries?
    • High-traffic APIs with complex filters may need performance benchmarking.
  4. Is sorting a critical feature?
    • The experimental status of sorting could delay adoption if it’s a core requirement.
  5. How will filter definitions be managed across similar models?
    • DRY principles may require abstract base models or shared traits.

Integration Approach

Stack Fit

  • Ideal for:
    • API-driven applications (REST/GraphQL) where dynamic filtering is common.
    • Admin dashboards with ad-hoc query parameters.
    • Search-heavy applications (e.g., e-commerce, SaaS platforms).
  • Less ideal for:
    • Read-heavy systems with simple, static queries.
    • Applications using raw SQL or non-Eloquent query builders.

Migration Path

  1. Assessment Phase:
    • Audit existing filtering logic (e.g., manual where() clauses, custom query scopes).
    • Identify models requiring filtering and their complexity (e.g., JSON fields, relationships).
  2. Pilot Implementation:
    • Start with one model (e.g., Product or User) to test integration.
    • Gradually replace custom filtering logic with Filterable trait.
  3. Incremental Rollout:
    • Phase 1: Basic filters ($eq, $like) for high-impact endpoints.
    • Phase 2: Complex filters ($jsonLength, $or/$and) for advanced use cases.
    • Phase 3: Deprecate legacy filtering logic post-validation.
  4. Testing:
    • Unit tests: Validate filter definitions and edge cases (e.g., empty values, invalid types).
    • Integration tests: Test API endpoints with filtered requests.
    • Performance tests: Benchmark query execution times under load.

Compatibility

  • Laravel 10+: Confirmed compatibility; no breaking changes expected for minor updates.
  • PHP 8.2+: Enables modern features like enums (FilterType), but may require PHP upgrades.
  • Database support:
    • PostgreSQL: Full support for JSON filters (e.g., $jsonLength).
    • MySQL: Limited JSON support (requires MySQL 5.7+ with JSON functions).
    • SQLite: JSON filters may not work without extensions.
  • Third-party packages:
    • Laravel Scout: May conflict if both packages define filterable models.
    • API resources: Ensure allowedFilters() doesn’t expose sensitive fields in serialized responses.

Sequencing

  1. Setup:
    • Install via Composer and publish config (php artisan eloquent-filtering:install).
    • Configure default filter behavior (e.g., case sensitivity for $like).
  2. Model Integration:
    • Add use Filterable; and define allowedFilters() in target models.
    • Start with simple filters (e.g., $eq, $gt) before complex ones.
  3. API Layer:
    • Update controllers to accept and pass filter arrays to Model::filter().
    • Example:
      $filters = request()->input('filters', []);
      $results = Product::filter($filters)->get();
      
  4. Client-Side:
    • Document filter structure for frontend teams (e.g., $eq vs. $like syntax).
    • Provide examples for common use cases (e.g., pagination + filtering).

Operational Impact

Maintenance

  • Pros:
    • Centralized filter definitions: Changes to filters are model-specific, reducing global refactoring.
    • Reduced boilerplate: Eliminates repetitive where() clauses in controllers.
    • Self-documenting: Filter definitions (allowedFilters()) serve as API documentation.
  • Cons:
    • Model bloat: Large models with many filters may become harder to read.
    • Dependency on package updates: Breaking changes in indexzer0/eloquent-filtering could require updates.
    • Debugging complexity: Dynamic queries may obscure SQL generation in logs.

Support

  • Pros:
    • Consistent behavior: Standardized filtering across the codebase.
    • Community support: Active GitHub repo with 224 stars and recent updates (2026).
    • Documentation: Comprehensive docs with examples and API references.
  • Cons:
    • Learning curve: Teams unfamiliar with Eloquent’s query builder may need training.
    • Sorting limitations: Experimental feature may require workaround documentation.
    • Error handling: Custom error messages for invalid filters must be implemented (e.g., unsupported target fields).

Scaling

  • Performance:
    • Optimizations needed for large datasets:
      • Use cursor() for pagination with filtered queries.
      • Add database indexes for frequently filtered fields (e.g., name, price).
      • Cache filter definitions if models are heavily reused.
    • Query complexity:
      • Avoid deep nesting of $or/$and conditions, which can bloat SQL.
      • Monitor slow queries with Laravel Debugbar or database profiling tools.
  • Horizontal scaling:
    • Stateless filtering logic works well in distributed environments (e.g., queue workers, API gateways).
    • Ensure filter definitions are versioned with model migrations.

Failure Modes

  • Runtime errors:
    • Invalid filter types: Catch with try-catch or validate input early.
    • Missing fields: Use Filter::field() with nullable defaults or fallback logic.
    • SQL errors: Wrap Model::filter() in transactions for critical operations.
  • Security:
    • Mass assignment risks: Sanitize request()->input('filters') to prevent deep nesting attacks.
    • Information leakage: Ensure allowedFilters() doesn’t expose sensitive fields (e.g., password).
  • Data integrity:
    • Filter misconfiguration: Test edge cases (e.g., empty arrays, non-existent fields).
    • Race conditions: Use optimistic locking ($model->fresh()) if filters affect concurrent writes.

Ramp-Up

  • Onboarding:
    • Developer training:
      • Workshop on Filterable trait and allowedFilters() syntax.
      • Hands-on exercise: Convert a model from manual where() clauses to the package.
    • Documentation:
      • Internal wiki with examples for common filters (e.g., $like:start).
      • API reference for frontend teams (e.g., filter payload structure).
  • Adoption barriers:
    • Legacy code: Gradual migration to avoid disrupting existing workflows.
    • Resistance to change: Highlight productivity gains (e.g., "reduced 50% of controller code
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.
aashan/pimcore-mcp-bundle
solution-forest/ai-kit-core
nexmo/api-specification
capell-app/block-library
axium/identity
cetria/laravel-dummy-models
cetria/reflection-helper
agropredict/sso-auth-bundle
evolvestudio/spam-protection
datacore/hub-sdk
develia/commons
cuci/prototurk-sdk
cuci/prototurk-sdk-symfony
develia/geo-bundle
dreamzy/livewire-charts
touchestate-sdk/php-sdk
22h/doctrine-garbage-collection-bundle
agtp/agtp-php
agtp/mod-php
splash/sonata-admin