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

Laravel Querybuilder Laravel Package

ghostcompiler/laravel-querybuilder

API-ready Eloquent query builder for Laravel with strict allow-lists for filters, sorts, includes, and sparse fields. Supports nested relation filters/sorting, custom filters, tenant scoping, safe public query interfaces, and pagination helpers for clean API responses.

View on GitHub
Deep Wiki
Context7

Technical Evaluation

Architecture Fit

  • Eloquent-Centric: The package is tightly integrated with Laravel’s Eloquent ORM, making it ideal for APIs built on top of Eloquent models. It enforces a schema-driven query interface, which aligns well with domain-driven design (DDD) and API-first architectures.
  • JSON:API Compliance: Supports sparse fieldsets, nested relation filters, and strict query validation—key for modern API design. This reduces over-fetching and improves performance.
  • Tenant-Aware Scoping: Useful for multi-tenant SaaS applications, where query constraints must be dynamically applied per tenant.
  • Policy-Aware Includes: Integrates with Laravel’s authorization policies, enabling fine-grained control over relation access (e.g., admins vs. regular users).

Integration Feasibility

  • Low Friction for Eloquent APIs: Requires minimal changes to existing query logic—primarily replacing raw where()/orderBy() calls with package methods (e.g., $query->allowFilter('status')).
  • Backward Compatibility: Works with Laravel 10–13 and PHP 8.1+, ensuring compatibility with modern Laravel stacks.
  • Custom Filter Support: Extensible via custom filter classes, allowing domain-specific logic (e.g., date ranges, full-text search).
  • Strict Mode: Prevents N+1 queries and over-fetching by validating all query parameters against allow-lists, reducing runtime errors.

Technical Risk

  • Schema Rigidity: Overly restrictive allow-lists may require frequent schema updates if API requirements evolve. Mitigate by designing schemas with future extensibility in mind.
  • Performance Overhead: Dynamic query building (e.g., nested relations) could introduce latency if not optimized. Benchmark with real-world query patterns before adoption.
  • Learning Curve: Developers must understand package conventions (e.g., allowFilter(), allowSort()) and custom filter logic. Provide internal documentation or workshops.
  • Dependency Lock: Package is MIT-licensed but has no dependents, indicating niche adoption. Monitor for upstream changes or forks if critical.

Key Questions

  1. API Maturity: Are our Eloquent models already well-defined with clear query requirements, or will schema design require significant upfront work?
  2. Customization Needs: Do we need custom filters (e.g., complex date logic, geospatial queries), or will built-in features suffice?
  3. Multi-Tenant Support: Will tenant-aware scoping be used, or is this a single-tenant application?
  4. Policy Integration: Are we leveraging Laravel’s gates/policies for relation access, or will allow-lists suffice?
  5. Testing Strategy: How will we validate query safety (e.g., preventing SQL injection) beyond the package’s built-in protections?
  6. Legacy Code: How will this integrate with existing APIs that use raw query parameters or dynamic SQL?

Integration Approach

Stack Fit

  • Ideal For:
    • API-first Laravel applications (REST/GraphQL).
    • SaaS platforms with multi-tenancy or role-based access.
    • Microservices where Eloquent is the primary data layer.
  • Less Ideal For:
    • Non-Eloquent data access (e.g., raw database queries, non-Laravel services).
    • Applications with highly dynamic query requirements (e.g., ad-hoc analytics).

Migration Path

  1. Phase 1: Pilot with a Single Model

    • Start with a non-critical Eloquent model (e.g., User, Product).
    • Replace raw query logic with package methods:
      // Before
      $query->where('status', 'active')->orderBy('created_at');
      
      // After
      $query->allowFilter('status')->allowSort('created_at');
      
    • Validate query behavior and performance against existing endpoints.
  2. Phase 2: Schema-Driven Refactor

    • Define allow-lists for filters, sorts, includes, and fields in model schemas.
    • Example schema for Product:
      public function getFilters(): array { return ['status', 'category_id']; }
      public function getSorts(): array { return ['name', 'price', 'created_at']; }
      
    • Use migration helpers to backfill existing queries.
  3. Phase 3: Policy & Tenant Integration

    • Implement policy-aware includes for sensitive relations.
    • Add tenant scoping if using Laravel Scout or similar.
  4. Phase 4: Full API Rollout

    • Gradually replace remaining endpoints.
    • Deprecate legacy query parameters via middleware (e.g., redirect to new format).

Compatibility

  • Laravel 10–13: Confirmed compatibility; test edge cases (e.g., Laravel 13’s query builder changes).
  • PHP 8.1+: Ensure strict typing and named arguments are used where applicable.
  • Third-Party Packages: Check for conflicts with:
    • API resource packages (e.g., spatie/laravel-api-resources).
    • Query builders (e.g., baum/baum for CMS).
    • Authentication (e.g., laravel/sanctum for tenant isolation).

Sequencing

Step Task Dependencies Risk Mitigation
1 Define schema allow-lists Model definitions Start with minimal allow-lists; expand iteratively.
2 Replace raw queries Pilot model Use feature flags to toggle old/new logic.
3 Add custom filters Domain logic Test edge cases (e.g., malformed input).
4 Integrate policies Auth system Mock policies during testing.
5 Tenant scoping Multi-tenancy setup Test with sample tenant data.
6 Deprecate legacy queries API versioning Use middleware to log warnings.

Operational Impact

Maintenance

  • Pros:
    • Reduced Bug Surface: Strict validation prevents invalid queries at the API layer.
    • Centralized Schema: Query rules live in models, making them easier to maintain than scattered middleware.
    • Auditability: Allow-lists serve as self-documenting API contracts.
  • Cons:
    • Schema Drift: Changes to query requirements may need model updates (e.g., adding a new filter).
    • Custom Filter Maintenance: Domain-specific filters require ongoing testing.

Support

  • Developer Onboarding:
    • Training Needed: Engineers must learn package conventions (e.g., allowFilter() vs. customFilter()).
    • Documentation Gap: Package lacks advanced use cases (e.g., nested relation performance tuning).
  • Debugging:
    • Clear Error Messages: Package rejects invalid queries early, but stack traces may obscure root causes.
    • Logging: Add query logging (e.g., query_builder.log channel) for auditing.
  • Community:
    • Limited Adoption: No dependents may mean fewer community solutions for edge cases.

Scaling

  • Performance:
    • Query Optimization: Package encourages selective field loading and relation eager-loading, reducing DB load.
    • Caching: Combine with Laravel’s query cache or Redis for frequent queries.
    • Load Testing: Validate under high concurrency (e.g., 10K+ requests/sec) with nested relations.
  • Database Impact:
    • Indexing: Ensure filter/sort columns are indexed (e.g., status, created_at).
    • Connection Pooling: Monitor DB connection usage with complex nested queries.

Failure Modes

Failure Scenario Impact Mitigation
Invalid Query Parameters 400 errors, API instability Use middleware to sanitize input before reaching package.
N+1 Queries in Nested Relations High DB load, timeouts Enforce with() allow-lists and use loadMissing().
Schema Mismatch Broken queries, 500 errors Implement schema validation in CI/CD.
Custom Filter Bugs Data corruption, leaks Unit test all custom filters with fuzz testing.
Tenant Isolation Failure Cross-tenant data leaks Use Laravel’s tenant middleware + package scoping.

Ramp-Up

  • Timeline Estimate:
    • Pilot (1–2 weeks): Schema design + 1 model.
    • Full Rollout (4–8 weeks): Gradual endpoint migration.
    • Optimization (2–4 weeks): Performance tuning, edge cases.
  • Key Metrics to Track:
    • Query Latency: Before/after adoption (target: <10% increase).
    • Error Rates: Invalid
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.
codifyo/ts-generator-bundle
andydefer/laravel-cluster
testo/fiber
mintobit/jobqueue
a4sex/maintenance-bundle
a4sex/entity-date-update
a4sex/client-identifier
a4sex/base-utilites
a4sex/key-value-storage
a4sex/micro-status
chilldev/dependency-injection-extra
datinglibre/datinglibre-app-api
biberltd/corebundle
bricre/symfony-bundle-test
biberltd/logbundle
dominium/http-adapter-bundle
dominium/google-analytics
a4sex/auto-clean-entity
christhompsontldr/laravel-inky
spatie/mailcoach-vapor