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 Query Builder Laravel Package

spatie/laravel-query-builder

Build safe, flexible Eloquent queries from incoming API requests. Supports whitelisted filtering (partial/exact/scope/custom), sorting, includes, field selection, pagination, and grouped AND/OR filters—ideal for JSON:API-style endpoints with minimal boilerplate.

View on GitHub
Deep Wiki
Context7

Technical Evaluation

Architecture Fit

  • Eloquent-Centric: Perfectly aligned with Laravel’s Eloquent ORM, enabling seamless integration into existing query logic without disrupting core architecture.
  • API-First Design: Built for API-driven filtering, sorting, and pagination, making it ideal for RESTful or GraphQL-like endpoints where dynamic query parameters are common.
  • Modularity: Supports granular control via AllowedFilter, AllowedSort, and AllowedInclude, enabling fine-tuned security and validation per endpoint.
  • Composability: Works alongside Laravel’s query builder, scopes, and relationships, allowing incremental adoption (e.g., wrapping existing queries).

Key Synergies:

  • Leverages Laravel’s built-in features (e.g., with(), orderBy(), where()) under the hood.
  • Adheres to JSON:API filtering conventions, reducing client-side complexity.
  • Supports nested relationships and custom logic via interfaces (e.g., Sort).

Integration Feasibility

  • Low Friction: Single-composer-install with zero config for basic use cases; minimal boilerplate for advanced features.
  • Backward Compatibility: Non-breaking changes (e.g., wrapping existing queries) ensure zero disruption to legacy code.
  • Testing Support: Built-in test utilities and CI/CD integration simplify validation.
  • Documentation: Comprehensive docs with feature-specific examples (e.g., custom sorts, nested includes) accelerate onboarding.

Potential Challenges:

  • Overhead for Simple APIs: May introduce unnecessary complexity for APIs with static queries.
  • Performance: Dynamic filtering/sorting can impact query planning; requires indexing and benchmarking.
  • Security: Requires explicit whitelisting of filters/sorts/includes to prevent injection (mitigated by design).

Technical Risk

Risk Area Mitigation
Query Injection Strict whitelisting via allowedFilters()/allowedSorts(); no raw SQL exposure.
Performance Degradation Profile with DB::enableQueryLog(); optimize indexes for filtered/sorted columns.
Version Lock-in MIT license + active maintenance (last release: 2026); upgrade path documented.
Custom Logic Complexity Interface-based extensions (e.g., Sort) allow controlled complexity.
Caching Invalidation Cache keys must include query parameters (e.g., Cache::remember("users_{$request->query()}", ...)).

Critical Questions:

  1. Does the API require dynamic field selection (fields[])? If yes, ensure database permissions align with allowed fields.
  2. Are there complex nested relationships? Test dot-notation includes (e.g., posts.comments) for depth limits.
  3. How will query parameters be validated? Use Laravel’s ValidatesRequests or middleware to sanitize inputs before QueryBuilder.
  4. What’s the fallback for unsupported parameters? Custom middleware to handle 422 errors or default behaviors.

Integration Approach

Stack Fit

  • Laravel Ecosystem: Native support for Eloquent, API resources, and testing tools (e.g., HttpTests).
  • API Layers: Ideal for:
    • GraphQL Resolvers: Dynamic filtering via QueryBuilder in resolver logic.
    • REST Controllers: Replace manual where() chains with declarative allowedFilters().
    • Admin Panels: Integrate with tools like Filament or Nova for UI-driven query building.
  • Microservices: Lightweight alternative to GraphQL for service-to-service queries.

Anti-Patterns:

  • Avoid using for read-heavy static queries (e.g., dashboards with fixed datasets).
  • Not suitable for raw SQL-heavy applications (e.g., complex joins not expressible via Eloquent).

Migration Path

Phase Action Items Tools/Dependencies
Assessment Audit existing queries for dynamic parameters; identify high-impact endpoints. telescope, DB::queryLog()
Pilot Replace 1–2 endpoints with QueryBuilder; compare performance. Benchmark, Laravel Debugbar
Incremental Rollout Wrap controllers/resources with QueryBuilder; update API docs. OpenAPI generator (e.g., darkaonline/l5-swagger)
Full Adoption Standardize on QueryBuilder for all dynamic queries; deprecate legacy logic. PHPStan, Pest for validation tests

Example Migration:

// Before: Manual filtering in controller
public function index(Request $request)
{
    return User::query()
        ->when($request->has('name'), fn($q) => $q->where('name', 'like', "%{$request->name}%"))
        ->when($request->has('sort'), fn($q) => $q->orderBy($request->sort))
        ->get();
}

// After: Declarative with QueryBuilder
public function index(Request $request)
{
    return QueryBuilder::for(User::class)
        ->allowedFilters('name')
        ->allowedSorts('name', 'created_at')
        ->get();
}

Compatibility

  • Laravel Versions: Tested on LTS versions (10.x, 11.x); check composer.json for constraints.
  • PHP Versions: Requires PHP 8.1+ (aligns with Laravel’s minimum).
  • Database: Works with all Eloquent-supported databases (MySQL, PostgreSQL, SQLite, etc.).
  • Third-Party Packages:
    • Conflict Risk: None identified; designed for composability.
    • Enhancements: Works with:
      • spatie/laravel-activitylog (filter by activity).
      • laravel-scout (filter by searchable attributes).

Sequencing:

  1. Core APIs: Start with public-facing endpoints requiring dynamic queries.
  2. Admin Panels: Integrate with UI tools (e.g., Filament’s Table components).
  3. Internal Services: Use for inter-service communication (e.g., UserService::findByCriteria()).

Operational Impact

Maintenance

  • Pros:
    • Centralized Rules: Filter/sort/include logic lives in one place (e.g., controller or service).
    • Validation: Built-in exception handling for invalid parameters (InvalidFilterQuery, etc.).
    • Testing: Mock QueryBuilder easily in unit tests (e.g., QueryBuilder::fake()).
  • Cons:
    • Documentation Burden: API specs must document allowed parameters (use OpenAPI/Swagger).
    • Deprecation Risk: Future Laravel Eloquent changes may require package updates.

Maintenance Tasks:

Task Frequency Tools
Update package dependencies Quarterly composer update + phpstan
Review allowed filters/sorts Bi-annually php artisan tinker (test queries)
Monitor query performance Monthly telescope, blackfire.io
Update API documentation Per release darkaonline/l5-swagger

Support

  • Debugging:
    • Query Dumping: Enable QueryBuilder::enableDumping() to log raw SQL.
    • Exceptions: Customize error responses (e.g., return 422 with allowed filters).
    • Logging: Log invalid requests for security audits.
  • Community:
    • Active GitHub issues (4.4K stars, 100+ open issues, but high response rate).
    • Spatie’s commercial support available for enterprise users.
  • SLAs:
    • Critical Bugs: ~24h response (based on issue tracker).
    • Feature Requests: ~1–2 months for major features.

Example Error Handling:

try {
    return QueryBuilder::for(User::class)
        ->allowedFilters('name')
        ->get();
} catch (InvalidFilterQuery $e) {
    return response()->json([
        'message' => 'Invalid filter',
        'allowed_filters' => ['name', 'email'],
    ], 422);
}

Scaling

  • Performance:
    • Indexing: Ensure filtered/sorted columns are indexed (e.g., name for LIKE queries).
    • Pagination: Use ->paginate() to avoid memory issues with large datasets.
    • Caching: Cache results with parameter-aware keys (e.g., Cache::remember("users_{$request->query()}", ...)).
  • Load Testing:
    • Simulate high concurrency with laravel-shift/laravel-queues-tester.
    • Monitor DB::connection()->getPdo()->getAvailableConnections() for connection pooling.
  • Horizontal Scaling:
    • Stateless design (no shared memory) works well with queues (e.g., laravel-horizon).
    • Database read replicas for scaling reads.

Benchmarking:

// Test with 10K users
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.
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
anil/file-picker
broqit/fields-ai