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

  • Decoupled Filtering Logic: The package abstracts complex query-building logic into reusable, model-specific filter definitions, aligning well with Laravel’s Eloquent ORM. This reduces boilerplate in controllers/APIs and centralizes filtering rules in models.
  • Declarative Design: The allowedFilters() method enforces a clear contract for filter definitions, improving maintainability and reducing runtime errors from invalid queries.
  • Query Builder Agnostic: While built for Eloquent, the package could theoretically integrate with other Laravel query builders (e.g., Query Builder) with minimal effort, though this isn’t natively supported.
  • HTTP Request Integration: Seamlessly maps incoming request data (e.g., ?name=TV&price[gt]=100) to Eloquent queries, ideal for APIs or search-heavy applications.

Integration Feasibility

  • Low Friction: Requires minimal changes to existing Eloquent models (add use Filterable trait and allowedFilters() method). No database migrations or schema changes needed.
  • API-First Friendly: Designed for HTTP request filtering, making it a natural fit for RESTful APIs, GraphQL resolvers, or admin dashboards.
  • Composite Queries: Supports $or/$and conditions out-of-the-box, enabling complex filtering without manual query chaining.

Technical Risk

  • Performance Overhead: Dynamic query building may introduce slight overhead for large datasets or complex filters. Benchmarking required for production-critical paths.
  • Sorting Immaturity: Documentation warns the sorting feature is in its infancy, which could limit use cases requiring advanced ordering.
  • JSON Path Complexity: Features like JSON_LENGTH rely on database-specific JSON functions (e.g., PostgreSQL’s json_length). Compatibility must be validated across target databases.
  • Validation Gaps: While filters are whitelisted via allowedFilters(), runtime validation of incoming filter values (e.g., type safety) is not enforced by the package.

Key Questions

  1. Database Compatibility: Does the target database (e.g., MySQL, PostgreSQL, SQLite) support all required JSON functions (e.g., json_length)?
  2. Filter Granularity: Will the predefined filter types ($eq, $gt, $like, etc.) cover 80% of use cases, or will custom filters need to be extended?
  3. Security: How will malicious or malformed filter inputs be sanitized? (e.g., SQL injection via target or value).
  4. Testing Strategy: How will filtered queries be tested in CI/CD? The package’s test suite covers core functionality, but integration tests for custom models are needed.
  5. Legacy Code Impact: How will existing queries (e.g., hardcoded where clauses) coexist with the new filtering system? Will a hybrid approach be necessary?

Integration Approach

Stack Fit

  • Laravel 10+: Native compatibility with Laravel’s service container, Eloquent, and request handling.
  • PHP 8.2+: Leverages modern PHP features (e.g., named arguments, enums) for cleaner syntax.
  • APIs/GraphQL: Ideal for filtering resources in APIs (e.g., GET /products?category=$eq:electronics) or GraphQL resolvers.
  • Admin Panels: Simplifies dynamic filtering in Laravel Nova or custom admin interfaces.

Migration Path

  1. Pilot Phase:
    • Start with a single high-impact model (e.g., Product or User) to validate the package’s fit.
    • Replace manual where clauses in controllers with Model::filter($request->all()).
  2. Incremental Adoption:
    • Gradually migrate models, prioritizing those with complex or duplicated filtering logic.
    • Use feature flags to toggle filtering behavior during transition.
  3. Custom Extensions:
    • Extend the package for unsupported use cases (e.g., custom filter types, database-specific optimizations).

Compatibility

  • Eloquent Models: Requires models to implement IsFilterable and use the Filterable trait.
  • Request Handling: Assumes filter input is structured as an array (e.g., $request->query() or $request->all()). May need middleware to normalize input (e.g., flatten nested arrays).
  • Database: Test JSON-related filters (e.g., JSON_LENGTH) on the target database to ensure compatibility.
  • Caching: If using query caching (e.g., Laravel’s query cache), ensure filtered queries are cacheable or bypass caching where needed.

Sequencing

  1. Setup:
    • Install the package (composer require indexzer0/eloquent-filtering).
    • Publish config (php artisan eloquent-filtering:install).
    • Update config/app.php to bind the package’s service provider.
  2. Model Integration:
    • Add use Filterable and allowedFilters() to target models.
    • Define allowed filters (e.g., Filter::field('name', [FilterType::EQUAL])).
  3. Controller/API Layer:
    • Replace manual filtering with Model::filter($request->query()).
    • Example:
      public function index(Request $request) {
          return Product::filter($request->query())->get();
      }
      
  4. Testing:
    • Write unit tests for allowedFilters() definitions.
    • Test edge cases (e.g., invalid filter types, empty inputs).
  5. Monitoring:
    • Log slow queries to identify performance bottlenecks.
    • Validate filter accuracy against manual queries.

Operational Impact

Maintenance

  • Pros:
    • Centralized Rules: Filter logic lives in models, reducing duplication across controllers/services.
    • Consistent Syntax: Standardized filter definitions (e.g., $eq, $like) simplify onboarding.
  • Cons:
    • Model Bloat: Large models may accumulate complex allowedFilters() definitions.
    • Dependency Risk: Package updates may introduce breaking changes (though MIT license mitigates this).

Support

  • Debugging:
    • Use toRawSql() to inspect generated queries.
    • Enable Laravel’s query logging (DB::enableQueryLog()) for complex filters.
  • Documentation:
    • Comprehensive docs exist, but custom extensions may require internal documentation.
  • Community:
    • Active GitHub repo (225 stars, recent releases) but limited dependents (0), indicating niche adoption.

Scaling

  • Performance:
    • Optimizations: Leverage database indexes on filtered fields (e.g., name, price).
    • Pagination: Combine with Laravel’s pagination (->paginate()) for large datasets.
    • Caching: Cache filtered results if queries are static (e.g., Product::filter($request->query())->remember(60)).
  • Load Testing:
    • Test under high concurrency to validate query performance (e.g., using $or/$and conditions).
    • Monitor memory usage for deeply nested filters.

Failure Modes

  • Invalid Inputs:
    • Malformed filter arrays (e.g., missing target or type) may cause silent failures or SQL errors.
    • Mitigation: Validate input in middleware or use Laravel’s Validator.
  • Database Errors:
    • Unsupported JSON functions (e.g., json_length) will fail on incompatible databases.
    • Mitigation: Feature flags or fallback logic for unsupported features.
  • Security:
    • Arbitrary target values could enable SQL injection (e.g., target="1 OR 1=1").
    • Mitigation: Whitelist allowed fields in allowedFilters() and sanitize inputs.
  • Sorting Issues:
    • Unstable sorting due to immature feature set.
    • Mitigation: Avoid sorting until the feature stabilizes or implement custom logic.

Ramp-Up

  • Developer Onboarding:
    • Training: Document the new filtering syntax and workflow for the team.
    • Examples: Provide code snippets for common use cases (e.g., filtering + sorting).
  • Migration Timeline:
    • Allocate 2–4 weeks for pilot testing and incremental rollout.
  • Tooling:
    • Integrate with IDE autocompletion (e.g., PHPStorm) for FilterType constants.
    • Add linting rules to enforce allowedFilters() definitions.
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.
hamzi/corewatch
minionfactory/raw-hydrator
hexters/coinpayment
rjcodes/rjcms
act-training/laravel-permissions-manager
alimarchal/laravel-chart-of-accounts
babenkoivan/elastic-scout-driver
mkwebdesign/filament-watchdog-v5
renatomarinho/laravel-page-speed
zedmagdy/filament-business-hours
renatovdemoura/blade-elements-ui
devgeek/beacon-admin
benjamin-rqt/data-watcher-bundle
atriumphp/atrium
sandermuller/package-boost-laravel
sandermuller/boost-skills
redaxo/core
yusufgenc/filament-api-forge
l3aro/rating-star-for-filament
leek/filament-subtenant-scope