# Repositories

- [Introduction](#introduction)
- [Where a repository lives](#where-a-repository-lives)
- [What a repository declares](#what-a-repository-declares)
- [Naming](#naming)
- [Narrowing every query](#narrowing-every-query)
- [What a response contains](#what-a-response-contains)
- [Serving under another prefix](#serving-under-another-prefix)
- [Public repositories](#public-repositories)
- [Middleware for one repository](#middleware-for-one-repository)
- [Configuration](#configuration)
- [Listing your repositories](#listing-your-repositories)

## Introduction

A repository is the API of one model. It's a type that implements `restify::Repository`. It names the model, the input that creates and updates it, the fields a response shows and clients may search, filter and sort by, and who may do what. Restify serves the endpoints and the MCP tools from it.

```rust
pub struct UserRepository;

impl Repository for UserRepository {
    type Model = User;
    type Store = NewUser;
    type Update = EditUser;

    fn fields() -> Vec<Field<User>> {
        vec![
            Field::new(User::name).searchable().sortable(),
            // Only an admin sees email addresses.
            Field::new(User::email).searchable().matchable().can_see(is_admin),
            Field::new(User::is_admin).matchable(),
            Field::new(User::email_verified_at).hide_from_index(),
            Field::new(User::created_at),
        ]
    }

    fn related() -> Vec<Related<User>> {
        vec![Related::through::<PostRepository>(User::posts, |user| &user.posts)]
    }

    /// Any logged-in user may read users. Nobody creates one here.
    async fn authorize(action: Action, request: &Request, user: Option<&User>) -> laravel::Result<()> {
        match (action, user) {
            (Action::AllowRestify | Action::Index | Action::Show, _) => Ok(()),
            (Action::Update, Some(user)) => request.authorize(UserPolicy::update, user).await,
            (Action::Delete, Some(user)) => request.authorize(UserPolicy::delete, user).await,
            _ => Err(laravel::abort(403)),
        }
    }
}
```

## Where a repository lives

Keep a repository in its model's file, such as `src/models/user.rs`, after the model, its policy and its input structs. Re-export it from `src/models/mod.rs`. One file then holds everything about how a model is stored and served.

## What a repository declares

Everything but the three types has a default.

| Item | Does | Default | Guide |
| --- | --- | --- | --- |
| `type Model` | The model the repository serves | Required | |
| `type Store` | The input that creates a model | Required | [Writing](writing.md) |
| `type Update` | The input that updates a model | Required | [Writing](writing.md) |
| `fn fields` | The attributes a resource shows, and the columns clients may search, filter and sort by | None, so a resource shows nothing | [Fields](fields.md) |
| `fn fields_for` | The attributes of one view, when they differ from `fields` | `fields()` | [Fields](fields.md#different-fields-for-one-view) |
| `fn uri_key` | The name in URLs and tool names | The table, in kebab-case | Below |
| `fn resource_type` | The `type` of a resource | The table | Below |
| `fn scopes` | Filters and sorts with their own queries | None | [Filtering](filtering.md#scopes) |
| `const PER_PAGE` | The page size when a request doesn't say | `15` | [Filtering](filtering.md#pagination) |
| `fn query` | Narrows every query the repository runs | The whole table | Below |
| `fn related` | The relationships clients may load with `?related=` | None | [Relationships](relationships.md) |
| `fn creating`, `fn updating` | Finish a write before it runs | Nothing | [Writing](writing.md#setting-columns-the-client-cant) |
| `fn stored`, `fn updated`, `fn deleted` | Run after a write | Nothing | [Writing](writing.md#after-a-write) |
| `fn authorize` | Who may do what | Refuses everything | [Authorization](authorization.md) |
| `fn actions` | Operations that may write, such as publishing a post | None | [Actions and getters](actions.md) |
| `fn getters` | Operations that only read, such as counting posts | None | [Actions and getters](actions.md) |
| `const MAX_BULK` | The most items one bulk request may hold | `100` | [Bulk operations](bulk.md) |
| `const RELATABLE_PER_PAGE` | How many models of this repository a related list loads for each record | `15` | [Relationships](relationships.md#limiting-lists-with-relatableperpage) |
| `fn soft_deletes` | The column of a soft-deleting model | None | [Soft deletes](soft-deletes.md) |
| `fn prefix` | A path to serve the repository under instead of the provider's prefix | None | Below |
| `fn middleware` | Middleware for this repository's endpoints only | None | Below |
| `const PUBLIC` | Serves the list, the show and the getters to guests | `false` | Below |
| `const MCP` | Which operations AI agents may run | `None`, so no tools | [MCP](mcp.md#letting-agents-use-a-repository) |

## Naming

A repository is named after its model's table: a `Post` model is served at `/api/restify/posts`, its resources have the type `posts`, and its MCP tools are `posts-index-tool`, `posts-show-tool` and so on, when it lets agents use it. A table with an underscore, such as `blog_posts`, is served at `/api/restify/blog-posts` and keeps the type `blog_posts`.

To choose other names, override `uri_key` and `resource_type`. Two repositories may then serve one model:

```rust
/// The logged-in user's own unpublished posts: a second repository over the `posts` table.
impl Repository for DraftRepository {
    type Model = Post;
    type Store = NewPost;
    type Update = EditPost;

    fn uri_key() -> String {
        "drafts".to_owned()
    }

    fn resource_type() -> &'static str {
        "drafts"
    }

    // ..
}
```

Two repositories can't have the same `uri_key`. The application refuses to start and names the duplicate.

## Narrowing every query

`query` receives the query before Restify adds search, filters and sorting to it, for the list and for finding one model alike. Use it when some rows must not exist for the API at all. `DraftRepository` serves only the logged-in user's unpublished posts:

```rust
use laravel::db::Builder;

/// Only the logged-in user's unpublished posts, whatever the request is for.
async fn query(query: Builder<Post>, request: &Request, _action: Action) -> laravel::Result<Builder<Post>> {
    let user: User = request.user().await?.or_abort(401)?;

    Ok(query.filter(Post::user_id.eq(user.id) & Post::published_at.is_null() & Post::deleted_at.is_null()))
}
```

To keep rows that have a related row, as PHP's `whereHas` and `orWhereHas` do, filter with `db::exists` and a subquery that names the outer table's column with `col`. Join it to other conditions with `|` (or) and `&` (and). The example app's `AuthorRepository` is PHP's `indexQuery` with `$query->where('id', $request->user()->id)->orWhereHas('posts')`:

```rust
use laravel::db::{self, Builder, col};

/// The list shows the logged-in user, and every user with a post that isn't deleted.
async fn query(query: Builder<User>, request: &Request, action: Action) -> laravel::Result<Builder<User>> {
    if action != Action::Index {
        return Ok(query);
    }
    let user: User = request.user().await?.or_abort(401)?;
    // PHP's `whereHas('posts')` leaves out soft-deleted posts, so the subquery does too.
    let wrote = db::exists(
        db::table("posts")
            .filter(col("posts.user_id").eq(col("users.id")))
            .filter(col("posts.deleted_at").is_null()),
    );

    Ok(query.filter(User::id.eq(user.id) | wrote))
}
```

When the related model uses soft deletes, PHP's `whereHas` skips its deleted rows. The subquery doesn't do that on its own: filter it with `col("posts.deleted_at").is_null()`, as above. Without it, a user would be listed because of a post that was deleted. See "Subqueries and exists" in the framework's `queries.md`.

A model that `query` leaves out answers `404` to show, update and delete, the same as a model that doesn't exist. Rows reached from another repository are narrowed too: a `Related::through` relationship that shows `DraftRepository` shows only the drafts its `query` keeps, and an attach, detach or sync finds only those rows (see [Who can see a relationship](relationships.md#who-can-see-a-relationship)). A `Related::raw` relationship asks no repository, so `query` doesn't narrow it. `action` says what the request is for, so a repository can narrow the list more than it narrows a show. An error `query` returns becomes the response.

## What a response contains

A resource has the model's key as `id`, the repository's `resource_type` as `type`, and the repository's fields as `attributes`, in the order `fields` lists them:

```json
{
    "data": {
        "id": "2",
        "type": "users",
        "attributes": {
            "name": "Bob Writer",
            "email": "bob@example.com",
            "is_admin": false,
            "email_verified_at": null,
            "created_at": "2026-01-01T10:00:00.000000Z"
        }
    }
}
```

The `id` is always a string. A column the repository lists no field for is never shown, whatever serde attributes the model has. See [Fields](fields.md) for which view shows which field, to whom, and how each type is written.

## Serving under another prefix

A repository is served under the provider's prefix, `/api/restify`, unless `prefix` names another path inside the `api` group. The example app serves its posts a second time, as bulletins, under `/api/v1`:

```rust
impl Repository for BulletinRepository {
    type Model = Post;
    type Store = NewBulletin;
    type Update = EditBulletin;

    fn uri_key() -> String {
        "bulletins".to_owned()
    }

    fn prefix() -> Option<&'static str> {
        Some("/v1")
    }
    // ...
}
```

Every endpoint of the repository is now under `/api/v1/bulletins`: the list, the show, the writes, the bulk endpoints, the actions and the getters. A request to the old path, such as `GET /api/restify/bulletins`, answers `403` "Unauthorized to use the route /api/restify/bulletins. Check prefix." after `Action::AllowRestify`. Another repository's name under `/api/v1`, such as `/api/v1/posts`, answers `404`.

PHP's `$prefix = 'api/v1'` becomes `Some("/v1")`, because Restify's routes are already in the `api` group. As in PHP, the `Location` header of a create and the list's `links.filters` still point under `/api/restify`.

## Public repositories

Set `PUBLIC` to serve the list, the show and the getters without the middleware you gave `Restify::authenticate`, as Restify for PHP's `$public = true` serves them without `auth:sanctum`:

```rust
impl Repository for LabelRepository {
    type Model = Label;
    type Store = NewLabel;
    type Update = EditLabel;

    /// The list, the show and the getters answer guests too.
    const PUBLIC: bool = true;

    /// Anyone reads labels. Only an admin creates, changes or deletes one.
    async fn authorize(action: Action, request: &Request, _label: Option<&Label>) -> laravel::Result<()> {
        match action {
            Action::AllowRestify | Action::Index | Action::Show => Ok(()),
            Action::Store | Action::Update | Action::Delete if is_admin(request).await? => Ok(()),
            _ => Err(laravel::abort(403)),
        }
    }
}
```

Everything else, such as creating, updating, deleting, the bulk endpoints and the actions, still answers `401` to a guest. `PUBLIC` has no effect on a repository with its own `prefix`.

On the public routes no token is read, so a client that sends one is still a guest, as in PHP. `authorize` is asked about guests, for the `meta` flags too, so it must not fail without a user: check `request.authenticated()` before `request.user()`, as `is_admin` does. Middleware added with `Restify::middleware`, such as a [gate](authorization.md#refusing-some-users-everywhere), still run.

## Middleware for one repository

`middleware` adds middleware that run before this repository's endpoints only, after the provider's, as Restify for PHP's `$middleware` does:

```rust
fn middleware() -> MiddlewareGroup {
    MiddlewareGroup::default().with(refuse_locked_requests)
}
```

A middleware that refuses a request answers before validation and before the model is looked up. Unlike PHP, a refusal comes before `Action::AllowRestify` is asked, because the middleware runs before the endpoint.

### Where the middleware run

| The repository's operation is reached through | Its middleware run |
| --- | --- |
| Its own routes, such as `GET /api/restify/labels` | Yes, around the endpoint |
| Its MCP tools, in `direct` mode and through `execute-operation` | Yes, before the tool |
| A nested route of another repository, such as `/api/restify/posts/1/comments` for the comments repository | Yes, before the operation. The route belongs to the parent, so the parent's middleware run too |
| `/api/restify/profile` and the profile tool, for the user repository | Yes, before the operation |
| `?related=` (or `include`) on another repository | **No** |
| The global search, `/api/restify/search` and the `global-search` tool | Yes, before the repository is searched. A refusal refuses the whole search, as in Restify for PHP |

Outside the repository's own routes, the middleware run as a check before the operation. A middleware may refuse, and the request then answers with the middleware's status and `message`. It may also change the request, such as adding an extension. But code it runs after `next.run(request)` doesn't run there, because no response passes back through it. Restify for PHP runs a repository's `$middleware` the same way.

Middleware are for things like rate limits, headers and maintenance switches. Don't use them for access control. A repository's rows can still be reached where its middleware don't run: through `?related=` on another repository. Decide who may see which rows in `authorize` and `query`, which every path asks.

## Configuration

Restify reads its settings from the environment, as the framework's own sections do, with the defaults of Restify for PHP's `config/restify.php`. Read them in code with `laravel::config().section::<restify::RestifyConfig>()`.

| Variable | Does | Default |
| --- | --- | --- |
| `RESTIFY_MAX_PER_PAGE` | The largest page a request may ask for | No limit |
| `RESTIFY_SERIALIZE_SHOW_META` | Whether a shown record carries `meta`; see [Authorization](authorization.md#what-the-user-may-do-with-a-record) | `true` |
| `RESTIFY_SERIALIZE_INDEX_META` | Whether a listed record carries `meta` | `false` |
| `RESTIFY_TOKEN_TTL` | How many minutes a login token lasts; see [Authentication](authentication.md) | Never expires |
| `FRONTEND_APP_URL` | Your frontend's address, which reset and verification links point to; see [Authentication](authentication.md#settings), which also lists `RESTIFY_PASSWORD_RESET_URL`, `RESTIFY_USER_VERIFY_URL`, `RESTIFY_PASSWORD_RESET_TIMEBOX` and `RESTIFY_REVOKE_TOKENS_ON_RESET` | None |
| `RESTIFY_MCP_MODE` | How the MCP server lists its tools: `wrapper` or `direct`; see [MCP](mcp.md#choosing-a-mode) | `wrapper` |
| `RESTIFY_MCP_READ_ONLY` | Whether the MCP server refuses every tool that writes; see [MCP](mcp.md#read-only-mode) | `false` |

`RestifyConfig` also has the settings of forgot password, reset password and email verification, such as `FRONTEND_APP_URL`: see [Authentication](authentication.md#settings). Its `search_case_sensitive` is PHP's setting of the same name: see [Search](filtering.md#search).

### Moving a PHP `config/restify.php`

Every key of PHP's file, and where it went:

| PHP key | Here |
| --- | --- |
| `base` | `Restify::new().prefix("/restify")`, inside the `api` group; see [Installation](installation.md#configuring-the-provider) |
| `middleware` | `Restify::authenticate` for `auth:sanctum`, and `Restify::middleware` for the others. `api` is already on the `api` group. `DispatchRestifyStartingEvent` sends an event nothing in a response depends on: leave it out. `AuthorizeRestify` is the gate of [Authorization](authorization.md#refusing-some-users-everywhere) |
| `pagination.max_per_page` | `RESTIFY_MAX_PER_PAGE` |
| `repositories.serialize_index_meta`, `serialize_show_meta` | `RESTIFY_SERIALIZE_INDEX_META`, `RESTIFY_SERIALIZE_SHOW_META` |
| `repositories.apply_main_query_to_actions_and_getters`, `apply_main_query_to_writes` | Not settings. `Repository::query` narrows every read, write, action and getter, as PHP does with both set to `true`, their default. It receives the `Action`, so a repository can skip the narrowing for some of them |
| `auth.token_ttl` | `RESTIFY_TOKEN_TTL` |
| `auth.user_model`, `auth.table`, `auth.provider` | The user type you give `Restify::auth::<R>()` and `Sanctum<User>` |
| `auth.frontend_app_url`, `password_reset_url`, `user_verify_url`, `password_reset_timebox`, `revoke_tokens_on_reset` | `FRONTEND_APP_URL`, `RESTIFY_PASSWORD_RESET_URL`, `RESTIFY_USER_VERIFY_URL`, `RESTIFY_PASSWORD_RESET_TIMEBOX`, `RESTIFY_REVOKE_TOKENS_ON_RESET`; see [Authentication](authentication.md#settings) |
| `search.case_sensitive` | `search_case_sensitive` (`RESTIFY_SEARCH_CASE_SENSITIVE`): `false` compares `upper(column)` with the term in capitals, as PHP does |
| `search.use_joins_for_belongs_to`, `sort.use_joins_for_belongs_to` | Not settings. To search or sort by a related model's column, write a `Scope::searching` or `Scope::sorting`; see [Scopes](filtering.md#scopes) |
| `logs.*` | Not served: Restify for PHP writes `action_logs` rows only for models that use its `HasActionLogs` trait, and this crate writes none |
| `repositories.cache.*`, `cache.policies.*` | Not served. Both are off by default in PHP and change no answer, only how often the database and the policies are asked |
| `restifyjs.*` | Not served: the `/restifyjs/setup` endpoint doesn't exist here |
| `ai_solutions.*` | Not applicable: PHP's AI suggestions for error pages |
| `mcp.mode`, `mcp.read_only` | `RESTIFY_MCP_MODE`, `RESTIFY_MCP_READ_ONLY` |
| `mcp.*` (the others) | The provider's MCP methods; see [MCP](mcp.md) |

## Listing your repositories

`laravel restify:list` prints each repository with its endpoint, its searchable, filterable and sortable columns, and the relationships clients may load. `laravel restify:list --json` prints the same as JSON, with each repository's fields and the name of each MCP tool. Both also list each repository's actions and getters. In code, inject `restify::Registry` to read the same list.
