Filtering | laravel-query-builder-go | Spatie       

 SPATIE  

laravel-query-builder-go
========================

spatie.be/open-source

  [Docs](https://spatie.be/docs)  [Laravel-query-builder-go](https://spatie.be/docs/laravel-query-builder-go/v1)  Features  Filtering

 Version   v1      

 Other versions for crawler [v1](https://spatie.be/docs/laravel-query-builder-go/v1) 

  Filtering    
- [ Requirements ](https://spatie.be/docs/laravel-query-builder-go/v1/requirements)
- [ Introduction ](https://spatie.be/docs/laravel-query-builder-go/v1/introduction)
- [ Installation and setup ](https://spatie.be/docs/laravel-query-builder-go/v1/installation-setup)
- [ Questions and issues ](https://spatie.be/docs/laravel-query-builder-go/v1/questions-issues)
- [ Testing ](https://spatie.be/docs/laravel-query-builder-go/v1/testing)
- [ Releasing ](https://spatie.be/docs/laravel-query-builder-go/v1/releasing)
- [ Changelog ](https://spatie.be/docs/laravel-query-builder-go/v1/changelog)
- [ Support us ](https://spatie.be/docs/laravel-query-builder-go/v1/support-us)
- [ About us ](https://spatie.be/docs/laravel-query-builder-go/v1/about-us)

Features
--------

- [ Filtering ](https://spatie.be/docs/laravel-query-builder-go/v1/features/filtering)
- [ Sorting ](https://spatie.be/docs/laravel-query-builder-go/v1/features/sorting)
- [ Including relationships ](https://spatie.be/docs/laravel-query-builder-go/v1/features/including-relationships)
- [ Selecting fields ](https://spatie.be/docs/laravel-query-builder-go/v1/features/selecting-fields)

Advanced usage
--------------

- [ Extending query builder ](https://spatie.be/docs/laravel-query-builder-go/v1/advanced-usage/extending-query-builder)
- [ Pagination ](https://spatie.be/docs/laravel-query-builder-go/v1/advanced-usage/pagination)
- [ Multi value delimiter ](https://spatie.be/docs/laravel-query-builder-go/v1/advanced-usage/multi-value-delimiter)
- [ Front-end implementation ](https://spatie.be/docs/laravel-query-builder-go/v1/advanced-usage/front-end-implementation)
- [ Differences from PHP ](https://spatie.be/docs/laravel-query-builder-go/v1/advanced-usage/port-differences)

 Filtering
=========

###  On this page 

1. [ Basic usage ](#content-basic-usage)
2. [ Disallowed filters ](#content-disallowed-filters)
3. [ Disable InvalidFilterQuery exception ](#content-disable-invalidfilterquery-exception)
4. [ Partial, beginsWith and endsWith filters ](#content-partial-beginswith-and-endswith-filters)
5. [ Exact filters ](#content-exact-filters)
6. [ Operator filters ](#content-operator-filters)
7. [ Exact or partial filters for related properties ](#content-exact-or-partial-filters-for-related-properties)
8. [ BelongsTo filters ](#content-belongsto-filters)
9. [ Scope filters ](#content-scope-filters)
10. [ Trashed filters ](#content-trashed-filters)
11. [ Callback filters ](#content-callback-filters)
12. [ Custom filters ](#content-custom-filters)
13. [ Filter aliases ](#content-filter-aliases)
14. [ Ignored filters values ](#content-ignored-filters-values)
15. [ Default Filter Values ](#content-default-filter-values)
16. [ Nullable Filter ](#content-nullable-filter)
17. [ Filter groups (OR / AND conjunction) ](#content-filter-groups-or--and-conjunction)

Basic usage
-----------------------------------------------------------------------------------------

The `filter` query parameter is used to filter results. Allowed filters must be explicitly specified using `AllowedFilters`. Independent filters combine with AND.

```
// GET /users?filter[name]=John&filter[email]=gmail
users, err := querybuilder.For(model.Query[User](), input).
    AllowedFilters(
        querybuilder.Partial[User]("name"),
        querybuilder.Partial[User]("email"),
    ).Get(r)
```

Pass `r` as the context in handlers. Jobs and commands pass their `ctx`. Model type parameters are your application types, not package-owned models.

Disallowed filters
--------------------------------------------------------------------------------------------------------------

Requests for filters not specified in `AllowedFilters` return a `*QueryError`. Use `errors.As` to inspect its `Kind`, `Unknown` and `Allowed` fields. Its HTTP status is 400. All requested filter, sort, include and root field names are checked before callbacks run.

Disable InvalidFilterQuery exception
--------------------------------------------------------------------------------------------------------------------------------------------------------------------

Go returns errors rather than throwing exceptions. Set `Config.IgnoreUnknownFilters = true` to ignore unknown filter names. This does not permit filtering by them. Known filters still apply.

Partial, beginsWith and endsWith filters
------------------------------------------------------------------------------------------------------------------------------------------------------------------------------

`Partial[User]("name")` matches literal substrings, ignoring case with SQL `LOWER`. `BeginsWith` and `EndsWith` match literal prefixes and suffixes using database case rules. Percent, underscore, exclamation and backslash input cannot add wildcard behavior.

Comma-separated text values match any member. Empty and nonscalar text list members are skipped. Native subqueries defer identifier quoting and wildcard escaping to the connection that executes the query. This also preserves an explicitly selected `.On(conn)` connection. These filters target columns of the model's own table. Use a callback for expressions or joined-table text columns.

Exact filters
-----------------------------------------------------------------------------------------------

Use exact filters for IDs and boolean properties:

```
query := querybuilder.For(model.Query[User](), input).
    AllowedFilters(querybuilder.Exact[User]("id"), querybuilder.Exact[User]("active"))
```

`filter[id]=1,2,3` produces an IN constraint. Exact scalars use equality. Literal `true` and `false` strings are recursively converted to booleans. Booleans inside a comma-separated string remain strings, matching PHP's normalization order. Values are bound parameters, never SQL fragments.

Operator filters
--------------------------------------------------------------------------------------------------------

```
query := querybuilder.For(model.Query[User](), input).
    AllowedFilters(querybuilder.Operator[User]("score", "dynamic"))
```

`filter[score]=>10,<=20` matches scores greater than 10 and at most 20. Static operators are `=`, `!=`, `<>`, `<`, `<=`, `>` and `>=`. Lists combine with AND. Use a `GroupOr` of operator filters for alternative conditions. A dynamic value without a prefix uses equality. An operator with an empty remainder compares to nil using the native builder's null semantics.

Exact or partial filters for related properties
-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------

Related models are statically typed. Instead of discovering a relationship from a dotted filter string, register a typed constraint:

```
filter := querybuilder.RelationFilter[User]("posts.title", "posts",
    func(q *model.Builder[Post], value any) *model.Builder[Post] {
        return q.Where("title", "=", value)
    },
)
query := querybuilder.For(model.Query[User](), input).AllowedFilters(filter)
```

Native `WhereHas` supports nested paths and avoids duplicate parents. The callback receives normalized input, which can be `[]any` for list input. Handle that shape explicitly, for example with `WhereIn`. Use `CallbackFilter` when you need to return an error from a lookup. A native polymorphic relationship constraint can run later, while the query executes.

BelongsTo filters
-----------------------------------------------------------------------------------------------------------

Filter a model's foreign key directly with `Exact[Post]("author", "user_id")`, or use `RelationFilter[Post, User]` with a native constraint on the related key. Explicit mapping supports custom column names and typed relationships without guessing foreign keys.

Scope filters
-----------------------------------------------------------------------------------------------

Go scopes are functions, not dynamically named model methods. Register a `CallbackFilter` that calls your scope with the normalized value. Use its context to resolve model arguments with `model.Find` or `model.FromRoute` in the handler. Return lookup errors instead of dropping the filter.

Trashed filters
-----------------------------------------------------------------------------------------------------

Laravel Go v0.1.0 does not install PHP's `SoftDeletes` global scope. For your own nullable deletion timestamp:

```
query := querybuilder.For(model.Query[User](), input).
    AllowedFilters(querybuilder.Trashed[User]("trashed", "deleted_at"))
```

`with` leaves the subject unchanged. `only` adds `IS NOT NULL`. Other values, and an absent parameter, add `IS NULL`. Start from an unscoped subject because a callback cannot remove a deletion constraint you already added.

Callback filters
--------------------------------------------------------------------------------------------------------

```
popular := querybuilder.CallbackFilter("popular",
    func(ctx context.Context, q *model.Builder[User], value any, column string) (*model.Builder[User], error) {
        return q.Where(column, ">", value), nil
    }, "score",
)
```

Callbacks can return errors unchanged. The context carries cancellation and the application's database transaction. Each top-level filter runs in a native scope so OR conditions cannot widen the subject's existing constraints.

Custom filters
--------------------------------------------------------------------------------------------------

Use an application's function or a method value as `FilterFunc[User]`. It may capture your own profile, repository or configuration. No package-specific subclass or service-container replacement is required. Custom sorts and includes expose the same native model builder.

Filter aliases
--------------------------------------------------------------------------------------------------

```
querybuilder.Exact[User]("public_name", "name")
```

Only `public_name` is accepted in requests. The database column name remains private unless you allow it separately.

Ignored filters values
--------------------------------------------------------------------------------------------------------------------------

```
querybuilder.Exact[User]("name").Ignore("all", "unknown")
```

Ignored values are removed recursively from arrays and objects. If all values are ignored, the filter is skipped, even when nullable. Repeated `Ignore` calls accumulate. Equality is type-strict in Go, except boolean input also matches its literal `"true"` or `"false"` ignored string. Pass individual ignored values rather than a nested slice.

Default Filter Values
-----------------------------------------------------------------------------------------------------------------------

```
querybuilder.Exact[User]("active").Default(true)
```

Defaults apply only when the parameter is absent. Explicit false, zero, empty or nil values do not trigger the default. `UnsetDefault()` removes it.

Nullable Filter
-----------------------------------------------------------------------------------------------------

```
querybuilder.Exact[User]("deleted_at").Nullable()
```

`Nullable` passes nil input through to the callback. An exact nil matches SQL NULL. `Default(nil)` also enables nullable filtering. URL `filter[name]=` is an empty string, not nil. Use `RequestData` for explicit JSON null or a custom callback for application-specific empty-value rules.

Filter groups (OR / AND conjunction)
--------------------------------------------------------------------------------------------------------------------------------------------------------------

### Basic usage

```
search := querybuilder.GroupOr("search",
    querybuilder.Partial[User]("name"),
    querybuilder.Partial[User]("email"),
)
```

`filter[search]=john` searches either member, enclosed in parentheses. The group's public name is the only request parameter exposed by this declaration.

### `groupAnd`

Use `GroupAnd` to require every member to match the same input.

### Multiple independent groups

Register several named groups in `AllowedFilters`. Each group stays parenthesized and combines with other top-level filters using AND.

### Combining with top-level filters

Application constraints and ordinary top-level filters remain outside the group. A search OR cannot bypass a tenant or active-user constraint.

### Mixed member types

Groups accept exact, partial, operator, relationship and callback filters. Member ignored values and explicit delimiter overrides still apply. The outer group's normalized input is not split a second time by the global delimiter.

### Validation

An empty group returns an error when applied. Member callback failures propagate to the caller. Input defaults belong to the group, not its members, because members all receive the group's explicit value.

 A good
match?
-------------

### What we do best

- All things Laravel
- Custom frontend components
- Building APIs
- AI-powered features
- Simplifying things
- Clean solutions
- Integrating services

### Not our cup of tea

- WordPress themes
- Cutting corners
- Free mockups to win a job
- "Just execute the briefing"

 In short: we'd like to be a **substantial part** of your project.

 [ Get in touch via email ](mailto:info@spatie.be?subject=A%20good%20match%21&body=Tell%20us%20as%20much%20as%20you%20can%20about%0A-%20your%20online%20project%0A-%20your%20planning%0A-%20your%20budget%0A-%20%E2%80%A6%0A%0AAnything%20that%20helps%20us%20to%20start%20straightforward%21)
