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

Laravel Query Builder Laravel Package

spatie/laravel-query-builder

Spatie's Laravel Query Builder turns incoming API request parameters into Eloquent queries, letting you define allowed filters, sorts, includes, and pagination so clients can shape responses through the URL without exposing dangerous query logic.

View on GitHub
Deep Wiki
Context7

spatie/laravel-query-builder builds Eloquent queries directly from API request parameters, letting you filter, sort, and include relationships without writing repetitive controller logic. Instead of manually parsing query strings, you declare what's allowed and the package handles the rest, keeping your API layer clean and secure by design.

It integrates seamlessly with Laravel's Eloquent models and supports filtering, sorting, relation inclusion, and pagination out of the box.

  • Filtering with partial, exact, scope, and custom filters
  • Grouped filters using AllowedFilter::groupOr() and groupAnd()
  • Sorting on single or multiple columns
  • Relationship includes via ?include=
  • Safe by default: only explicitly allowed parameters are applied
Frequently asked questions about Laravel Query Builder
How do I install spatie/laravel-query-builder in a Laravel app?
Run composer require spatie/laravel-query-builder; the service provider is auto-discovered, so there is nothing to register and no config file to publish for baseline usage. You only need an existing Laravel application with Eloquent models. Adoption is opt-in per endpoint: wrap a controller query in QueryBuilder::for() and add your allowed filters, sorts, and includes. Endpoints that never call the package behave exactly as before.
Which Laravel and PHP versions does laravel-query-builder v7 support?
The v7 line is the current major and targets recent Laravel releases on supported PHP versions. Exact constraints live in the package composer.json on Packagist, so read them before upgrading Laravel or PHP. Treat the major version as part of your upgrade plan: pin it in composer.json and check the changelog for breaking changes, since newer filter features land in minor releases.
How do I control which filters and sorts an API request is allowed to use?
The package is whitelist-first: only properties declared in allowedFilters, allowedSorts, allowedIncludes, and allowedFields are applied. A request asking for anything else throws InvalidFilterQuery, InvalidSortQuery, or InvalidIncludeQuery instead of silently changing the query. Start from a model class or an existing builder and chain the allowed lists per endpoint. Keep those lists close to the controller so reviewers can see exactly what each endpoint exposes.
How do I add a custom filter or an OR group of filters?
Implement the Spatie\QueryBuilder\Filters\Filter interface and register it with AllowedFilter::custom('name', new YourFilter), or use the built-in partial, exact, and scope helpers when they already fit. For grouped logic, AllowedFilter::groupOr() and AllowedFilter::groupAnd() accept any allowed filter types and broadcast a single request value to every member. Both grouping helpers are relatively recent additions, so pin the package version and cover the generated SQL with a test rather than assuming behaviour matches older filter types.
Why does an invalid filter or sort return a 500 error?
InvalidFilterQuery, InvalidSortQuery, and InvalidIncludeQuery are exceptions, and Laravel renders unhandled exceptions as 500 responses. Map them to a 400 in your exception handler, or in bootstrap/app.php withExceptions, and return a consistent error envelope. Doing this once at the framework level keeps error budgets clean and stops clients from reading a bad query string as a server outage.
Is it safe to use orderByRaw in a custom sort with user input?
No. The documented custom-sort pattern interpolates a column name into raw SQL, which is only safe when that column is a server-side constant passed to AllowedSort::field(). Never let a request value reach the raw SQL string, and treat any diff that does as a security defect in code review. Prefer the default field sorts and reserve raw ordering for whitelisted columns you control.
How do I keep query builder endpoints fast in production?
Every column you allow as a filter or sort should be indexed, because filtering on an unindexed column is a direct path to a full table scan and request timeouts. Cap page size, since paginate() takes a per-page value, and cap include depth, because a short URL with nested includes and Count/Exists sorts can generate heavy joins and subqueries. Measure p95 query cost per collection endpoint and revisit the allowed lists as models evolve, because the package has no way to know your indexes.
Does laravel-query-builder respect my existing scopes, policies, and multi-tenancy?
QueryBuilder::for() accepts a pre-built Eloquent builder as well as a model class and returns a chainable builder, so it composes with existing where clauses, global scopes, soft deletes, and tenancy scoping. The safest pattern is to build the scoped, authorized query first and hand that builder to the package. Verify with tests that authorization cannot be bypassed through an include, since relationship includes reach data outside the root model.
How should I test endpoints built with laravel-query-builder?
Use feature tests that call the endpoint with real query strings and assert the JSON response, including status codes for disallowed filters and sorts. Add contract tests around allowedFields, because silently dropping an attribute can break downstream consumers. Also assert result counts or generated SQL for relationship includes and grouped filters so regressions in the query are caught.
When should I not use spatie/laravel-query-builder, and what are the alternatives?
It is a thin translation layer from query parameters to Eloquent, so it does not fit GraphQL APIs, non-Eloquent data sources, or domains where filtering semantics encode business rules that belong in a domain service. Alternatives are hand-written request-to-scope mapping in controllers, JSON:API-focused packages, or GraphQL tooling such as Lighthouse when clients need flexible field selection. For typical REST collection endpoints on Laravel, this package is usually the cheapest way to get whitelisted filtering, sorting, includes, and pagination.
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.
dbravoan/dbcms-admin-theme-dbcms
dbravoan/dbcms-theme-db-cyber
dbravoan/dbcms-blocks-basic
dbravoan/dbcms-module-content-audit
dbravoan/dbcms-module-ai-assistant
paygate-to/paygate-php
padosoft/askmydocs-connector-base
defstudio/supercharged-carbon
bernskioldmedia/laravel-matomo
bernskioldmedia/laravel-harvest
bernskiold/laravel-data-scrubber
bernskiold/laravel-currency-converter
bernskiold/laravel-campaign-monitor
bernskioldmedia/laravel-autotranslate
siberfx/telegram-bot
roy-sandip/laravel-view-extended
gregsphotography/site-builder-core
roy-sandip/laravel-view
anodyne/blade-fluentui-icons
webx-ui/module-catalog-collections