# Filtering

- [Introduction](#introduction)
- [Search](#search)
- [Filters](#filters)
- [Sorting](#sorting)
- [Scopes](#scopes)
- [Advanced filters](#advanced-filters)
- [Listing the filters](#listing-the-filters)
- [Grouping](#grouping)
- [Global search](#global-search)
- [Pagination](#pagination)
- [Columns a repository doesn't list](#columns-a-repository-doesnt-list)

## Introduction

A list endpoint, such as `GET /api/restify/posts`, takes its options from the query string. A client may only search, filter and sort by the [fields](fields.md) the repository marks for it. Every other parameter is ignored, as Restify for PHP ignores it. Each value is read with the column's own type before it reaches the database.

The query string is read as Laravel reads it: when a parameter is sent twice, the last one wins; values are trimmed; and an empty value, such as `?search=`, counts as not sent.

```
GET /api/restify/posts?search=rust&featured=true&sort=-votes&perPage=10&page=2
```

The `posts-index-tool` MCP tool takes `page`, `perPage`, `search`, `sort`, `include` and each filter column as arguments, as in Restify for PHP. It has no arguments for the filters with a leading `-`. See [MCP](mcp.md#the-tools-in-direct-mode).

Mark a field with what clients may do with its column:

```rust
fn fields() -> Vec<Field<Post>> {
    vec![
        Field::query_only(Post::id).searchable().matchable().sortable(),
        Field::new(Post::title).searchable().matchable().sortable(),
        Field::new(Post::body).searchable().matchable().hide_from_index(),
        Field::new(Post::votes).matchable().sortable(),
        // ..
    ]
}
```

A parameter is named after the column, whatever the field's `label` is. To let clients filter or sort by a column that no response shows, list it with `Field::query_only`.

A field with `can_see` is only searched, filtered and sorted for the requests its gate lets see it. For other requests, its column is ignored, as if the repository didn't declare it. See [Showing a field to some users](fields.md#showing-a-field-to-some-users).

When two fields name the same column, such as one shown and one hidden, the first one that says `searchable`, `matchable`, `sortable` or `groupable` decides it. The column is searched, filtered and sorted once, and listed once in `/filters` and in the MCP tools, as PHP lists it once in `$search`, `$match` and `$sort`.

## Search

`?search=rust` keeps the rows where any `searchable` column contains `rust`. It uses SQL `like`. Whether upper and lower case count depends on the database:

- SQLite ignores case for the letters A to Z.
- PostgreSQL ignores case (Restify uses `ilike`).
- MySQL and MariaDB follow the column's collation. Their usual collations, such as `utf8mb4_0900_ai_ci`, ignore case and accents. A `_bin` or `_cs` collation tells `Rust` from `rust`.

Set `RESTIFY_SEARCH_CASE_SENSITIVE=false` to ignore case on every database and with any collation. The search then compares `upper(column)` with the term in capitals, as Restify for PHP does with `search.case_sensitive` off. The default is `true`, as in PHP.

A column that isn't text, such as `Post::id` above, is searched as text. When the key is searchable and the term is a key, such as `?search=4`, the row with key 4 is kept too.

As in Restify for PHP:

- `%` and `_` in the term are wildcards, so `?search=%` keeps every row.
- `?search=0` is treated as empty, so it searches nothing.
- A repository with no searchable field ignores `?search=` and returns the whole list.

## Filters

A `matchable` field lets clients filter by its column. How a value compares depends on the field's kind of match, which the column's type picks. `matchable_as` picks another kind:

```rust
Field::new(Post::user_id).matchable_as(MatchKind::Array),
Field::new(Post::rating).decimals(2).matchable_as(MatchKind::Between),
```

| Kind | Picked by | Request | Keeps the rows where |
| --- | --- | --- | --- |
| `Text` | `String`, `Uuid`, `Ulid`, `f64`, `Decimal` | `?title=Restify` | `title` is exactly `Restify`, upper and lower case included |
| `Integer` | Every integer type a column can have: `i8` to `i64` and `u8` to `u64`, as in a new application's `u64` keys | `?votes=10` | `votes` is 10 |
| `Bool` | `bool` | `?featured=true` | `featured` is true. `?featured=false` or `0` also keeps the rows where it's `NULL` |
| `Datetime` | `Timestamp`, `civil::Date` | `?published_at=2026-01-05` | `published_at` is on that day |
| | | `?published_at=2026-01-01,2026-01-06` | `published_at` is from the start of the first day to the start of the second |
| `Between` | | `?rating=2,4` | `rating` is from 2 to 4, both included |
| `Array` | | `?user_id=1,3` | `user_id` is 1 or 3 |

These forms work with every kind:

| Request | Keeps the rows where |
| --- | --- |
| `?body=null` | `body` is `NULL` |
| `?-body=null` | `body` isn't `NULL` |
| `?-votes=10` | `votes` isn't 10. Rows where it's `NULL` aren't kept either, as in SQL |
| `?filter[votes]=10`, `?filter[-votes]=10` | The same as `?votes=10` and `?-votes=10` |

Several filters combine with "and". When a request sends both `?votes=` and `?-votes=`, only the negated one counts.

An `Integer` filter reads the number at the start of the value, as PHP's `(int)` does: `?votes=10,20` keeps the rows with 10 votes, and `?votes=many` keeps those with 0. A number the column's type can't hold keeps no rows, and its negation keeps every row with a value: `?milestone_id=-1` on a `u64` column, or `?votes=300` on an `i8` one. A `u64` column holds numbers up to `i64::MAX` here, because PostgreSQL and SQLite store no larger ones. Any other value that isn't of the column's type, such as `?published_at=soon`, keeps no rows too.

A repository with no `matchable` field and no matching scope can still be filtered by its key, compared as `Text`: `?id=2`. Restify for PHP does the same.

To filter by a column of your own type, implement `restify::Property` for it and set its `MATCH` kind and its `parse`, which turns a filter's text into a value to compare. The trait's documentation shows each.

## Sorting

A `sortable` field lets clients sort by its column. `?sort=votes` and `?sort=+votes` sort ascending, and `?sort=-votes` descending. `?sort=-votes,title` sorts by several columns in order.

- A list without `?sort=` is sorted by the key, newest first.
- After the sorts a request asks for, rows that tie are sorted by the key, in the direction of the last sort. So a page never repeats or skips a row.
- Where `NULL` goes is up to the database. SQLite, MySQL and MariaDB put it first when sorting ascending; PostgreSQL puts it last.
- How text sorts is up to the database too. SQLite compares the letters' codes, so every capital comes before `a`. MySQL's and MariaDB's usual collations ignore case, so `lowercase notes` comes among the titles that start with `L`. Restify for PHP sorts the same way on each database.
- A repository with no `sortable` field and no sorting scope can still be sorted by its key, but only under its table's name, such as `?sort=tags.id`. `?sort=id` is ignored there, as in Restify for PHP.

## Scopes

A scope is a filter or a sort with its own query, for what a column alone can't say. List them in `Repository::scopes`:

```rust
fn scopes() -> Vec<Scope<Post>> {
    vec![
        // `?longer_than=100` keeps the drafts whose body has more than 100 characters.
        Scope::matching("longer_than", |query, value, negated| {
            let length = value.parse::<i64>().unwrap_or(0);

            query.filter(if negated {
                db::raw!("length(coalesce(body, '')) <= {length}")
            } else {
                db::raw!("length(coalesce(body, '')) > {length}")
            })
        }),
        // `?sort=popular` puts the drafts with the most votes first.
        Scope::sorting("popular", |query, descending| {
            query.order_by(if descending { Post::votes.asc() } else { Post::votes.desc() })
        }),
    ]
}
```

A matching scope gets the query, the parameter's value, and whether the client negated it with `?-longer_than=`. A sorting scope gets the query and whether the client asked for `?sort=-popular`. A scope wins over a field with the same name. Bind the value, as `db::raw!` does, and never paste it into SQL.

`Scope::searching` adds a condition to `?search=`. A row is kept when any searchable column or any searching scope matches. Use it to search a related model, as Restify for PHP's `BelongsTo::make('user')->searchable('name')` does:

```rust
// `?search=ada` also keeps the posts whose author's name contains "ada".
Scope::searching("user", |term| author_name().into_expr().like(format!("%{term}%"))),
// `?sort=users.attributes.name` sorts by the author's name.
Scope::sorting("users.attributes.name", |posts, descending| {
    let name = author_name();
    posts.order_by(if descending { name.desc() } else { name.asc() })
}),
```

Here `author_name()` is a subquery: `db::table("users").select([col("users.name")]).filter(col("users.id").eq(col("posts.user_id"))).limit(1)`.

As in Restify for PHP, the first part of a dotted sort name is made plural: `?sort=user.attributes.name` finds the scope named `users.attributes.name`. `?sort=user.name` finds nothing and is ignored.

## Advanced filters

An advanced filter takes a value that isn't a plain column value, such as a list of authors or a comparison with an operator. It is Restify for PHP's `AdvancedFilter`. The client sends the filters as a JSON list, encoded in base64, in `?filters=`:

```
[{"key": "votes", "value": 20, "operator": ">="}]
GET /api/restify/articles?filters=W3sia2V5Ijoidm90ZXMiLCJ2YWx1ZSI6MjAsIm9wZXJhdG9yIjoiPj0ifV0=
```

Or as plain JSON, in the body of `POST /api/restify/articles/apply-restify-advanced-filters`:

```json
{ "filters": [{ "key": "votes", "value": 20, "operator": ">=" }] }
```

Both answer the same page as the list. List each filter as a scope:

```rust
fn scopes() -> Vec<Scope<Post>> {
    vec![
        Scope::advanced(
            Filter::select("status", |posts, value, _| match value.as_str() {
                Some("published") => posts.filter(Post::published_at.is_not_null()),
                Some("draft") => posts.filter(Post::published_at.is_null()),
                _ => posts,
            })
            .title("Status")
            .description("Published or draft posts.")
            .option("Published", "published")
            .option("Draft", "draft"),
        ),
        Scope::advanced(
            Filter::value("votes", votes_compared)
                .title("Votes Filter")
                .meta("operators", [">=", "<=", "="]),
        ),
    ]
}
```

A filter's function may be a closure or a named function. Either gets the query, the item's `value`, and the rest of the item without `key` and `value`, such as `operator`, and returns the query. `votes_compared` above is the example app's:

```rust
/// The votes compared with the payload's `operator`, `>=` unless it is `<=` or `=`.
fn votes_compared(posts: Builder<Post>, value: &Value, rest: &Map<String, Value>) -> Builder<Post> {
    let votes = value
        .as_i64()
        .or_else(|| value.as_str().and_then(|text| text.parse().ok()))
        .unwrap_or_default();

    match rest.get("operator").and_then(Value::as_str) {
        Some("<=") => posts.filter(Post::votes.le(votes)),
        Some("=") => posts.filter(Post::votes.eq(votes)),
        _ => posts.filter(Post::votes.ge(votes)),
    }
}
```

`Value` and `Map` are `serde_json`'s, and `Builder` is `laravel::db::Builder`.

Several items may have the same key. Each applies, in the order sent, so `[{"key": "votes", "value": 10, "operator": ">="}, {"key": "votes", "value": 20, "operator": "<="}]` is a range. An item whose key no filter has is ignored.

The constructor names the filter's `type` in the listing: `Filter::value` (`value`), `boolean`, `select`, `multiselect` and `timestamp`.

`value` is the item's `value` exactly as the client sent it, or `null` when the item has none. Restify doesn't change its shape, and neither does PHP. These are the values that Restify for PHP's recordings send:

| Filter | Item | `value` |
| --- | --- | --- |
| `boolean` | `{"key": "featureds", "value": {"featured": true}}` | An object, one key per option: read it with `value.get("featured")` |
| `select` | `{"key": "status", "value": "published"}` | A string: `value.as_str()` |
| `timestamp` | `{"key": "published-after", "value": "2026-01-04"}` | A string |
| `multiselect` | `{"key": "authors", "value": [2]}` | A list |
| `value` | `{"key": "votes", "value": 20, "operator": "<="}` | Anything. Here a number, and `operator` is in the rest |

In PHP, `filter()`'s `$value` is the same value, and `$this->input('featured')` reads one key of it, as `value.get("featured")` does.

| Method | Does |
| --- | --- |
| `.title(..)`, `.description(..)`, `.placeholder(..)` | The texts the listing shows |
| `.option(label, value)` | One choice the listing shows |
| `.meta(key, value)` | An extra key in the listing, such as `operators` |
| `.rules(listed, rules)` | Validates a value that is a JSON object or list. A failure answers `422` with the field errors. `listed` is the rules as the listing shows them, such as `json!({"featured": ["required", "boolean"]})` |
| `.can_see(gate)` | Hides the filter from users the gate refuses. An item naming it is ignored |

`rules` is the framework's `Rules`, with one `.field(..)` for each key of the value.

The framework has no rule named `boolean`. Laravel's `boolean` accepts `true`, `false`, `0`, `1`, `"0"` and `"1"`. `Rule::one_of(["0", "1"])` is not the same: it reads a JSON `false` as an empty text, so it refuses `false`. Write Laravel's rule as a custom rule instead. The example app keeps it in its `php` module:

```rust
pub struct Boolean;

impl ValidationRule for Boolean {
    async fn validate(&self, field: &Input<'_>) -> Result<(), RuleError> {
        match field.value {
            Some(InputValue::Bool(_)) => Ok(()),
            Some(InputValue::Number(number)) if matches!(number.as_i64(), Some(0 | 1)) => Ok(()),
            Some(InputValue::String(text)) if matches!(text.as_str(), "0" | "1") => Ok(()),
            _ => Err(field.reject("The :attribute field must be true or false.")),
        }
    }
}
```

Then use it with `Rule::custom`:

```rust
Filter::boolean("featureds", |posts, value, _| {
    posts.filter(Post::featured.eq(truthy(value.get("featured"))))
})
.title("Featured Filter")
.option("Featured", "featured")
.rules(
    json!({ "featured": ["required", "boolean"] }),
    Rules::new().field("featured", [Rule::required(), Rule::custom(php::Boolean)]),
),
```

`restify:import` writes the same `php::Boolean` for a PHP filter that lists `boolean`.

PHP filters often compare dates with `whereDate`. Call `.date()` on the column, then compare. The example app's `published-after` filter is PHP's `$query->whereDate('published_at', '>', $value)`:

```rust
Filter::timestamp("published-after", |posts, value, _| {
    match value.as_str().and_then(|day| day.parse::<Date>().ok()) {
        Some(day) => posts.filter(Post::published_at.expr().date().gt(day)),
        None => posts,
    }
})
.title("Published After Filter")
.placeholder("YYYY-MM-DD"),
```

PHP's `now()->toDateString()` is `laravel::time::today()`. So `whereDate('due_date', '<', now()->toDateString())` is `db::col("due_date").date().lt(laravel::time::today())`, or shorter, `db::col("due_date").is_before_today()`. See "Dates" in the framework's `queries.md`, and its `time.md`.

As in Restify for PHP:

- Items whose `key` names no filter the user can see are ignored, and so are items that aren't JSON objects.
- `?filters=` is read even when it isn't valid base64: characters outside the base64 alphabet are skipped. JSON `null` applies no filters. A JSON object is read as the list of its values.
- A value is validated only when it is a JSON object or list.
- The filters run after the search and the column filters, and before grouping and sorting.

Filters that can't be read answer `422`, as a validation error of `filters` with a message that says what to send:

- `?filters=` that still isn't JSON once decoded, or is JSON but a number, a string or a boolean.
- On `apply-restify-advanced-filters`, a body whose `filters` is a string, a number or a boolean. A body without `filters` uses `?filters=` instead, decoded as on `GET`.

Restify for PHP answers each of these with a `500`, which is a bug in PHP. A client that sent valid filters sees no difference.

The example app's `ArticleRepository`, in [`example/src/models/article.rs`](https://github.com/BinarCode/laravel-restify-rust/blob/main/example/src/models/article.rs) of the Restify for Rust repository, has one filter of each type.

## Listing the filters

`GET /api/restify/articles/filters` lists the advanced filters the user can see, in the order of `scopes`:

```json
{ "data": [
  { "type": "select", "advanced": true, "title": "Status", "description": "Published or draft posts.",
    "placeholder": null, "column": null, "key": "status", "rules": [],
    "options": [{ "label": "published", "property": "Published" }, { "label": "draft", "property": "Draft" }] }
] }
```

An option's `label` is the value to send and its `property` the text to show. Restify for PHP names them that way round, and so does this crate.

- `?include=matches,sortables,searchables` adds the list's own parameters after the advanced filters: each `matchable` field and matching scope, each `sortable` field and sorting scope, and each `searchable` field. Scopes whose name has a dot aren't listed, and neither are searching scopes.
- `?only=matches` lists only those, without the advanced filters. An empty or unknown name lists nothing.

A repository that refuses `Action::AllowRestify` answers `403`.

## Grouping

`?group_by=user_id` groups the list by a column the repository marks `groupable`:

```rust
Field::query_only(Post::id).groupable(),
Field::new(Post::user_id).groupable(),
```

Several columns are comma-separated. Any other column answers `422`: "The column [title] is not allowed for grouping. Allowed columns are: id, user_id". A repository with no groupable field refuses every column. A grouped list isn't sorted by the key after the requested sorts.

The list selects every column, so grouping by a column that isn't the key only works on SQLite and MariaDB. PostgreSQL and MySQL refuse it, and the request answers `500`, as it does in Restify for PHP. MySQL refuses it because of its `ONLY_FULL_GROUP_BY` mode, which is on by default and which Laravel's `strict` connections keep on.

## Global search

`GET /api/restify/search?search=rust` searches several repositories at once, as Restify for PHP's global search does. A repository takes part when it implements `GlobalSearch` and the provider lists it, after the repository itself:

```rust
Restify::new()
    .repository::<PostRepository>()
    .global_search::<PostRepository>()
```

```rust
impl GlobalSearch for PostRepository {
    const RESULTS: u64 = 3;

    fn title(post: &Post) -> String {
        post.title.clone()
    }

    fn subtitle(post: &Post) -> Option<String> {
        Some(format!("{} votes", post.votes))
    }
}
```

Each repository runs its own list query, with its search, filters and sorts, and returns at most `RESULTS` (5 by default) rows that the user may see. Repositories that refuse `Action::AllowRestify` are skipped. Results come in the order of the repositories' type names:

```json
{ "data": [
  { "repositoryName": "posts", "repositoryTitle": "Posts", "title": "Restify", "subTitle": "30 votes",
    "repositoryId": 2, "link": "/api/restify/posts/2" }
] }
```

`title` defaults to the key, `subtitle` to `null`, and `label` (the `repositoryTitle`) to the URI key in words. Unlike Restify for PHP, where every repository is searched unless it opts out, a repository is left out until it opts in.

A repository served under its own [prefix](repositories.md#serving-under-another-prefix) is searched like any other, and its `link` uses that prefix, such as `/api/v1/bulletins/2`. Restify for PHP refuses the whole search with a `403` as soon as one such repository takes part, which is a bug in PHP.

What the search asks, as in Restify for PHP: `Action::AllowRestify` for each repository, then the repository's own `middleware()`, `Repository::query` for `Action::Index`, and `Show` for each row it returns. If one repository's middleware refuses, the whole search answers with that refusal. It doesn't ask `Action::Index` itself. So a user whose `Index` is refused, but who may see some rows, still finds those rows here. This is kept because PHP clients may rely on it. Safe setup: keep rows a user may not list out of `Repository::query`, or refuse `Show` for them, or refuse `AllowRestify` for that user.

Agents run the same search with the `global-search` MCP tool. See [MCP](mcp.md#searching-every-repository).

## Pagination

| Parameter | Does | Default |
| --- | --- | --- |
| `page` or `page[number]` | The page to return | `1` |
| `perPage` or `page[size]` | How many models a page holds | `PER_PAGE`, which is `15` |

Change the default on the repository:

```rust
const PER_PAGE: u64 = 25;
```

A value that isn't a whole number above 0, such as `?perPage=0` or `?page=abc`, is ignored, so the default applies. A decimal is cut to a whole number: `?perPage=2.9` means 2. A page past the last one is empty. `page[size]` wins over `perPage`, and once a request sends any `page[..]` parameter, only `page[number]` names the page. `per_page` isn't read, as Restify for PHP doesn't read it.

A request may ask for any page size unless the application sets `RESTIFY_MAX_PER_PAGE`, as with Restify for PHP. With `RESTIFY_MAX_PER_PAGE=100`, a larger `perPage` returns 100 models. `0` means no limit.

The response's `meta` has `current_page`, `from`, `to`, `per_page`, `last_page` and `total`, and its `links` has the URLs of the `first`, `prev` and `next` pages, which carry the page number and no other parameter, as in Restify for PHP. See [Reference](reference.md#a-page).

## Columns a repository doesn't list

A request that filters or sorts by a column the repository doesn't mark for it is answered as if that parameter weren't there. `?internal_notes=leak` returns the whole list, and `?sort=body` the default order. This is what Restify for PHP does, so clients can send extra parameters, such as a cache-buster `?_=1700000000`.

The column never reaches the query. A field whose `can_see` refuses the user is ignored in the same way. But a field that `hide_from_index` or `fields_for` leaves out of a view can still be searched, filtered and sorted, so its values can be guessed: mark only columns whose values a client may see.

`?group_by=` with a column the repository doesn't mark `groupable` answers `422`. See [Grouping](#grouping).
