# Restify for Laravel for Rust: the complete guides > Every guide of the `laravel-restify` crate, inlined. Generated by `site/tools/build.py` from the crate's README.md and docs/ folder. Version 0.1, on crates.io. # Restify for Laravel for Rust JSON:API endpoints and MCP tools from your [Laravel for Rust](https://laravel.com/rust) models. Describe a model's API once, in a repository. Restify serves it to people over HTTP and to AI agents over the Model Context Protocol, with the same authorization and validation for both. > Version 0.2, on `laravel-rust` 0.2. ## Example ```rust use laravel::model::model; use laravel::prelude::*; use laravel::time::Timestamp; use laravel::validation::Sometimes; use restify::{Action, Field, McpTools, Repository, Restify, Schema}; #[model] pub struct Post { pub id: i64, pub title: String, pub body: Option, #[default] pub votes: i64, pub created_at: Timestamp, pub updated_at: Timestamp, } /// What a client sends to create a post. Only these fields can be written. #[laravel::input(fills = Post)] #[validate(anyone)] #[derive(Schema)] pub struct NewPost { /// The post's headline. #[validate(required, max_length(255))] pub title: String, /// The post's text. pub body: Option, } /// What a client sends to change a post. A field left out keeps its value. #[laravel::input(fills = Post)] #[validate(anyone)] #[derive(Schema)] pub struct EditPost { /// The post's headline. #[validate(required, max_length(255))] pub title: Sometimes, /// The post's text. Send `null` to clear it. pub body: Sometimes>, } pub struct PostRepository; impl Repository for PostRepository { type Model = Post; type Store = NewPost; type Update = EditPost; /// AI agents may list posts and read one, through the MCP server. const MCP: Option = Some(McpTools::INDEX.show(true)); /// What a post shows, and the columns clients may search, filter and sort by. fn fields() -> Vec> { vec![ Field::new(Post::title).searchable().sortable(), Field::new(Post::body).searchable().hide_from_index(), Field::new(Post::votes).matchable().sortable(), Field::new(Post::created_at), ] } /// Anyone may read posts. Nobody may write them. async fn authorize(action: Action, _request: &Request, _post: Option<&Post>) -> laravel::Result<()> { match action { Action::AllowRestify | Action::Index | Action::Show => Ok(()), _ => Err(laravel::abort(403)), } } } pub fn configure() -> laravel::foundation::ApplicationBuilder { Application::configure().with_providers(|providers| { providers.add(Restify::new().repository::()); }) } ``` That application serves: | Request | Does | | --- | --- | | `GET /api/restify/posts` | Lists a page: `?search=`, `?votes=10`, `?-votes=10`, `?sort=-votes`, `?page=`, `?perPage=` | | `GET /api/restify/posts/{id}` | Shows one | | `POST /api/restify/posts` | Creates one | | `PUT` or `POST /api/restify/posts/{id}` | Changes one, checking every field's rules | | `PATCH /api/restify/posts/{id}` | Changes the fields it sends | | `DELETE /api/restify/posts/{id}` | Deletes one | | `POST /mcp/restify` | An MCP server where AI agents list posts and read one, as `const MCP` allows | ## What you get - **One definition, two audiences.** The MCP tools run the same code as the endpoints. - **Closed by default.** A repository refuses every request until its `authorize` method allows it. A response shows only the fields the repository lists, clients can only write the fields of the input structs, and only search, filter and sort by the fields marked for it. - **Typed.** A field is one of the model's typed columns, so a wrong column is a compile error and a wrong value is a `422`. - **Made for AI agents.** `#[derive(Schema)]` turns an input struct, its doc comments and its validation rules into the schema an agent reads. Errors come back as results an agent can correct. - **The same JSON as Restify for PHP**: `data` with `id`, `type` and `attributes`, and `meta` and `links` for a page. - **Pay only for what you use.** The MCP server and the OpenAPI document are Cargo features, `mcp` and `openapi`, both on by default. Turn them off and their code and dependencies leave your binary. See [Choosing features](installation.md#choosing-features). ## Documentation The guides ship inside the crate, in [`docs/`](documentation.md), so they match the installed version: [installation](installation.md), [repositories](repositories.md), [fields](fields.md), [filtering](filtering.md), [relationships](relationships.md), [writing](writing.md), [files and images](files.md), [actions and getters](actions.md), [authorization](authorization.md), [Sanctum tokens](sanctum.md), [authentication](authentication.md), [soft deletes](soft-deletes.md), [bulk operations](bulk.md), [MCP](mcp.md), [OpenAPI](openapi.md), [reference](reference.md), [testing](testing.md), [troubleshooting](troubleshooting.md) and [migrating from Restify for PHP](migrating-from-php.md). For AI coding agents, run `laravel restify:install` in an application once `Restify::new()` is registered in its providers: the command comes with the provider. It writes two skills to `.agents/skills`, and the same files to `.claude/skills` for Claude Code's slash commands: one that tells an agent how to work with Restify and where the guides are, and one that moves a Restify for PHP application to Rust. To start a migration from the PHP application, `php artisan restify:rust-install` from the Composer package `binarcode/laravel-restify-rust-migrate` writes that second skill there. --- # Restify Documentation Restify serves JSON:API endpoints and MCP tools for your Laravel for Rust models. You describe a model's API once, in a repository, and Restify serves it to people and to AI agents with the same rules. These guides ship inside the `laravel-restify` crate, so they always match the version an application has installed. - [Installation](installation.md): add Restify to an application and serve a first model. - [Repositories](repositories.md): everything a repository can declare. - [Fields](fields.md): what a resource shows, in which view and to whom, and how each type is written. - [Filtering](filtering.md): search, filters, sorting and pagination of a list. - [Relationships](relationships.md): loading a model's related models with `?related=`. - [Writing](writing.md): the input that creates and updates a model, validation, and hooks. - [Files and images](files.md): file uploads, where they are saved, how they are shown, and deleting them. - [Actions and getters](actions.md): operations beyond list, show, create, update and delete, such as publishing a post. - [Authorization](authorization.md): API tokens, and who may do what. - [Sanctum tokens](sanctum.md): keep the Laravel Sanctum tokens of a PHP application working after it moves to Rust, and create new ones. - [Authentication](authentication.md): the register, login, logout, password reset, email verification and profile endpoints of Restify for PHP. - [Soft deletes](soft-deletes.md): hide deleted rows, and mark rows deleted instead of removing them. - [Bulk operations](bulk.md): creating, updating and deleting many models in one request, all or nothing. - [MCP](mcp.md): the tools AI agents get, and how to connect an agent. - [OpenAPI](openapi.md): the OpenAPI 3.1 document of the endpoints, for API clients and SDK generators. - [Reference](reference.md): every endpoint, parameter, response shape and status code. - [Testing](testing.md): testing endpoints, tools and commands. - [Before you go to production](production.md): the settings to check before the first deploy. - [Troubleshooting](troubleshooting.md): compiler errors and unexpected responses, with their fixes. - [Migrating from Restify for PHP](migrating-from-php.md): move a PHP Restify API to Rust, and prove it answers the same. ## For AI coding agents Run `laravel restify:install` once in an application. It writes a skill to `.agents/skills/building-apis-with-restify` that tells an agent how to work with Restify and where these guides are, and the skill `restify-migrate`, which moves a Restify for PHP application to Rust. It writes the same files to `.claude/skills`, where Claude Code finds them as `/building-apis-with-restify` and `/restify-migrate`. In a PHP application, `php artisan restify:rust-install` writes `restify-migrate` ([Migrating from Restify for PHP](migrating-from-php.md#with-an-ai-coding-agent)). Run `laravel restify:list --json` to see what an application serves. ## Status Restify for Laravel for Rust is at version 0.2, on `laravel-rust` 0.2. --- # Installation - [Requirements](#requirements) - [Framework versions](#framework-versions) - [Creating the application](#creating-the-application) - [Adding the crate](#adding-the-crate) - [Choosing features](#choosing-features) - [Registering the provider](#registering-the-provider) - [Installing the agent skill](#installing-the-agent-skill) - [Serving a first model](#serving-a-first-model) - [Configuring the provider](#configuring-the-provider) ## Requirements - A Laravel for Rust application on `laravel-rust` 0.2, with the database driver feature for your database: `database-postgres`, `database-mysql` (MySQL and MariaDB) or `database-sqlite`. Restify is tested on PostgreSQL 18, MySQL 8.4, MariaDB 12.3 and SQLite. For MariaDB, start `DATABASE_URL` with `mariadb://`, so the framework writes MariaDB's SQL. To make one, see [Creating the application](#creating-the-application). - Rust 1.99 or later. ### Framework versions Each version of Restify is built for one minor version of the framework, and requires its exact release in its own `Cargo.toml`: | Restify (`laravel-restify`) | Framework (`laravel-rust`) | | --- | --- | | 0.2.x | 0.2.x (0.2.0 exactly) | | 0.1.x | 0.1.6 exactly | Your application's `laravel-rust` line must name the same minor version as the Restify you add: `"0.2"` for Restify 0.2. Cargo picks the release Restify requires within that minor version. It never moves your application from one minor version to another: with `laravel-rust = "0.2"` in your application and Restify 0.1's `"=0.1.6"`, Cargo builds two copies of the framework, and the build fails, because your models are the 0.2 framework's and Restify's traits are the 0.1 framework's. A new application from the starter is on the newest framework, so it takes the newest Restify. To see the versions in use, run `cargo tree -i laravel-rust`. To move an application to a newer Restify, follow the "Upgrading" part of its section in `CHANGELOG.md`, in the [Restify for Rust repository](https://github.com/BinarCode/laravel-restify-rust/blob/main/CHANGELOG.md). ## Creating the application Skip this if you have one. Create a new application with the Laravel CLI, as the framework's own `installation.md` shows (install the CLI first, from that guide): ```shell laravel new my-api --rust cd my-api ``` `laravel --version` must start with `Laravel CLI`. Laravel Herd's `laravel` command, and the older installer from Composer, are other programs, without `--rust`. Without the Laravel CLI, copy the official starter application with Git. It is the same application, and it needs only Git and Rust: ```shell git clone --depth 1 --branch 0.x https://github.com/laravel/rust.git my-api cd my-api rm -rf .git && git init cargo run -- key:generate ``` `key:generate` creates `.env` from `.env.example` and writes a new `APP_KEY`. The starter's `0.x` branch follows the newest framework release. For an older framework, clone the starter's tag for it instead, such as `--branch v0.1.3` for `laravel-rust` 0.1. The new application uses PostgreSQL. For another database, replace `database-postgres` in the `laravel-rust` line of `Cargo.toml` with `database-mysql` or `database-sqlite`, and set `DB_CONNECTION` and `DATABASE_URL` in `.env`. The starter's `.cargo/config.toml` sends most of the build to `~/.cargo/build/laravel-rust`, a cache that every Laravel application on the machine shares (the framework's `development.md`, "The shared build cache"), not to `target/`. Clean one application with `cargo clean --workspace`. A plain `cargo clean` deletes the shared cache too. If you build in a container that is thrown away after each run, set `CARGO_BUILD_BUILD_DIR` to a folder you keep, or delete the `build-dir` line to keep the whole build in `target/`. ## Adding the crate Add it from [crates.io](https://crates.io/crates/laravel-restify): ```shell cargo add laravel-restify ``` The package is named `laravel-restify`, and your code imports it as `restify`. ### Choosing features The MCP server and the OpenAPI document are Cargo features, both on by default. Turn off the ones your application doesn't use, and their code and dependencies leave your binary: | Feature | Adds | Default | | --- | --- | --- | | `mcp` | The MCP server and its tools, `.mcp(..)` and `.without_mcp()`, and the `rmcp` crate | On | | `openapi` | The OpenAPI document, `.openapi(..)`, `.openapi_version(..)` and the `restify:openapi` command | On | The JSON:API endpoints, the `restify:install` and `restify:list` commands, actions, getters, bulk endpoints and relationships are always there. To keep only the endpoints, turn off the default features: ```toml [dependencies] laravel-restify = { version = "0.2", default-features = false } ``` To keep the endpoints and the MCP server, without the OpenAPI document: ```toml laravel-restify = { version = "0.2", default-features = false, features = ["mcp"] } ``` With `mcp` off, `Registry::mcp` is `None`, `RepositoryInfo::tools` is empty, and `restify:list` says the MCP server is turned off. With `openapi` off, `Registry::openapi` is `None` and the `restify:openapi` command doesn't exist. A call to `.without_mcp()` or `.openapi(..)` with its feature off doesn't compile: turn the feature on, or remove the call. What each feature costs in build time and binary size is measured in `bench/README.md` in the [Restify for Rust repository](https://github.com/BinarCode/laravel-restify-rust). ## Registering the provider Register the `Restify` service provider in `src/app.rs` right away, even before it serves a repository. Restify's commands, such as `restify:install`, come with the provider: until it is registered, the application says the command is unknown. ```rust Application::configure() .with_providers(|providers| { providers.add(restify::Restify::new()); }) ``` If `src/app.rs` already calls `.with_providers(..)`, add the `providers.add(..)` line inside it. ## Installing the agent skill If AI coding agents work on your application, install the Restify skill once, after [registering the provider](#registering-the-provider): ```shell laravel restify:install ``` The command writes two skills to `.agents/skills/`, and lists them in your `AGENTS.md` when you have one. It writes the same files to `.claude/skills/`, because Claude Code reads skills only from there, and only skills there become slash commands such as `/restify-migrate`. Other agents read `.agents/skills/`. `building-apis-with-restify` tells an agent the rules of a repository and where to find these guides for your installed version. `restify-migrate` takes an agent through moving a Restify for PHP application to this one ([Migrating from Restify for PHP](migrating-from-php.md)). To start that migration from the PHP application instead, `php artisan restify:rust-install` writes the same skill there. Running the command again updates the skill and changes nothing else. Run it again after you upgrade Restify. ## Serving a first model Restify needs three things for a model: an input struct for creating it, an input struct for updating it, and a repository that lists the fields to show. This example serves a `Post` model with a `title` and a nullable `body`. ```rust // src/models/post.rs use laravel::prelude::*; use laravel::validation::Sometimes; use restify::{Action, Field, Repository, Schema}; #[laravel::input(fills = Post)] #[validate(anyone)] #[derive(Schema)] pub struct NewPost { #[validate(required, max_length(255))] pub title: String, pub body: Option, } #[laravel::input(fills = Post)] #[validate(anyone)] #[derive(Schema)] pub struct EditPost { #[validate(required, max_length(255))] pub title: Sometimes, pub body: Sometimes>, } pub struct PostRepository; impl Repository for PostRepository { type Model = Post; type Store = NewPost; type Update = EditPost; /// What a post shows. A column without a field stays private. fn fields() -> Vec> { vec![ Field::new(Post::title).searchable().sortable(), Field::new(Post::body).searchable().hide_from_index(), Field::new(Post::created_at), ] } async fn authorize(action: Action, _request: &Request, _post: Option<&Post>) -> laravel::Result<()> { // Anyone may read. Nobody may write yet. match action { Action::AllowRestify | Action::Index | Action::Show => Ok(()), _ => Err(laravel::abort(403)), } } } ``` Register the repository with the `Restify` provider in `src/app.rs`, in place of the bare `Restify::new()`: ```rust use restify::Restify; Application::configure() .with_providers(|providers| { providers.add(Restify::new().repository::()); }) ``` The application now serves `GET /api/restify/posts`, `GET /api/restify/posts/{id}`, and an MCP server at `POST /mcp/restify`. The MCP server has no tools for posts until `PostRepository` sets `const MCP`. See [MCP](mcp.md#letting-agents-use-a-repository). To see everything it serves: ```shell laravel restify:list ``` A repository refuses every request until its `authorize` method allows it, and shows nothing of the model until `fields` lists it. This is deliberate: an API that nobody decided to open stays closed. To let users write, see [Authorization](authorization.md). For what a field can do, see [Fields](fields.md). ## Configuring the provider | Method | Does | Default | | --- | --- | --- | | `.repository::()` | Serves a repository's endpoints and tools | None | | `.authenticate(m)` | Runs the middleware that authenticates users before every endpoint and MCP request, except the reads of a public repository | None | | `.middleware(m)` | Runs a middleware before every endpoint and MCP request | None | | `.prefix("/v1")` | Changes the path of the endpoints, inside the `api` group | `/restify` | | `.mcp("/mcp/shop")` | Changes the path of the MCP server (feature `mcp`) | `/mcp/restify` | | `.without_mcp()` | Serves no MCP server (feature `mcp`) | Served | | `.openapi("/openapi.json")` | Serves the [OpenAPI document](openapi.md) at a path inside the prefix (feature `openapi`) | Not served | | `.openapi_version("2.0.0")` | Changes the document's `info.version` (feature `openapi`) | `1.0.0` | | `.auth::()` | Serves register, login and logout for the users of repository `R`; see [Authentication](authentication.md). A new application needs the [tokens table's migration](authentication.md#the-tokens-table) | Not served | | `.password_reset::()` | Serves forgot and reset password; see [Authentication](authentication.md#forgot-and-reset-password) | Not served | | `.email_verification::()` | Emails a link at registration, and serves the link; see [Authentication](authentication.md#verifying-emails) | Not served | | `.profile::()` | Serves the logged-in user's profile; see [Authentication](authentication.md#the-profile) | Not served | The framework opens 10 database connections at most (`DB_MAX_CONNECTIONS`). In the benchmark, with the database on the same machine, a larger pool served no more requests: the server ran out of processor first. Raise it when requests wait for the database instead, such as when the database is on another machine. An application refuses to start when two repositories have the same name. Override `Repository::uri_key` on one of them. Before the first deploy, read [Before you go to production](production.md). --- # 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> { 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> { vec![Related::through::(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, request: &Request, _action: Action) -> laravel::Result> { 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, request: &Request, action: Action) -> laravel::Result> { 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::()`. | 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::()` and `Sanctum` | | `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. --- # Fields - [Introduction](#introduction) - [Showing a column](#showing-a-column) - [Which view shows a field](#which-view-shows-a-field) - [Showing a field to some users](#showing-a-field-to-some-users) - [Computed fields](#computed-fields) - [Changing what a field shows](#changing-what-a-field-shows) - [Different fields for one view](#different-fields-for-one-view) - [How each type is written](#how-each-type-is-written) - [Mistakes the application refuses to start with](#mistakes-the-application-refuses-to-start-with) ## Introduction A field is one attribute of a resource. `Repository::fields` lists them, in the order a response shows them. A response shows nothing of the model that no field lists, so a new column stays private until you add its field. ```rust fn fields() -> Vec> { vec![ // No response shows the key as an attribute: it is the resource's `id`. Field::query_only(Post::id).searchable().matchable().sortable(), Field::new(Post::user_id).matchable_as(MatchKind::Array), Field::new(Post::title).searchable().matchable().sortable(), Field::new(Post::body).searchable().matchable().hide_from_index(), Field::computed("excerpt", |post: &Post| post.body.as_deref().unwrap_or_default().limit(20)), Field::new(Post::votes).matchable().sortable(), Field::new(Post::featured) .as_integer() .matchable() .can_see(is_admin) .can_store(is_admin) .can_update(is_admin), Field::new(Post::rating).decimals(2).matchable_as(MatchKind::Between), Field::new(Post::published_at).matchable().sortable(), Field::new(Post::created_at).sortable(), ] } ``` The same list says which columns clients may search, filter and sort by: see [Filtering](filtering.md). What clients may write is decided by the input structs, and narrowed by the field's write gates: see [Writing](writing.md). ## Showing a column `Field::new(Post::title)` shows the model's `title` column as the attribute `title`. The column is typed, so a column that doesn't exist doesn't compile. Restify reads the value from the model's field, not from its JSON, so the model's serde attributes don't change what a field shows. | Constructor | Shows | | --- | --- | | `Field::new(Post::title)` | A column | | `Field::computed("excerpt", \|post: &Post\| ..)` | A value computed from the model | | `Field::computed_with("is_mine", is_mine)` | A value computed from the model and the request | | `Field::query_only(Post::id)` | Nothing. Clients may filter or sort by the column | | `Field::file(Document::attachment)`, `Field::image(Document::cover)` | The path of an uploaded file, or its URL. Clients upload the file in a `multipart/form-data` request. See `files.md` | ## Which view shows a field There are four views: a list and one record, each over HTTP and as an MCP tool's answer. The answer of an endpoint that creates or updates shows what a list shows. The answer of an MCP tool that creates or updates shows the fields its input may write, as one record shows them. | Method | Leaves the field out of | | --- | --- | | `.hide_from_index()` | Lists, and the answers to a create or an update | | `.hide_from_show()` | One record | | `.hide_from_mcp()` | Every answer of an MCP tool | `PostRepository` hides the post's body from lists, where the excerpt is enough. ## Showing a field to some users `can_see` takes a gate: a `bool`, or an async function from the request to `laravel::Result`. A request that doesn't pass it gets the resource without the field, not an error. ```rust /// Whether the request's user administers the blog. Fields use it as their `can_see`. pub async fn is_admin(request: &Request) -> laravel::Result { // The login and register routes have no guard, and there `request.user()` fails. A guest // isn't an admin. if !request.authenticated().await? { return Ok(false); } let user: Option = request.user().await?; Ok(user.is_some_and(|user| user.is_admin)) } Field::new(User::email).searchable().matchable().can_see(is_admin) ``` A gate runs once for a request, not once for each row of a list, so it can't depend on the model. For a value that depends on both, use `computed_with`. `can_see` also closes the field's column to search, filters and sorting for the requests it refuses. If a user can't see `email`, then `?search=`, `?email=` and `?sort=email` ignore that column for them, the same way they ignore a name the repository doesn't declare. Otherwise a user could guess a hidden value one letter at a time. This applies to the global search too. Restify for PHP still searches, filters and sorts by a hidden field. That is a deliberate difference. `?search=` doesn't escape `%` and `_`, as in Restify for PHP. They act as wildcards: `?search=%` matches every row. They only reach columns the request may see. `can_store`, `can_update`, `can_patch` and `readonly_when` take a gate too. They decide who may write the field: a refused key is dropped from the input, and the rest of the write goes through. See [Writing](writing.md#fields-only-some-users-may-write). ## Computed fields `Field::computed` takes a name and a function from the model: ```rust Field::computed("excerpt", |post: &Post| post.body.as_deref().unwrap_or_default().limit(20)) ``` `Field::computed_with` takes an async function from the model and the request. It runs once for each record a response shows, so keep it cheap: the framework caches the request's user, and a query here runs for every row. ```rust async fn is_mine(post: &Post, request: &Request) -> laravel::Result { let user: Option = request.user().await?; Ok(user.is_some_and(|user| user.id == post.user_id)) } Field::computed_with("is_mine", is_mine) ``` Clients can't write, search, filter by or sort by a computed field. ## Changing what a field shows | Method | Does | | --- | --- | | `.label("headline")` | Names the attribute. The column's name stays the name of the filter and the sort | | `.default("Nothing written yet.")` | Shows this value when the field's is `null` | | `.resolve(\|value, post\| ..)` | Changes the JSON before it is shown. It runs before `default` | | `.as_integer()` | Shows a boolean as `0` or `1` | | `.decimals(2)` | Shows a number as a string with exactly two decimals, such as `"4.50"` | | `.description("..")` | Describes the attribute in the OpenAPI document | ```rust Field::new(Post::title).label("headline").sortable(), Field::new(Post::body).default("Nothing written yet."), ``` ## Different fields for one view When one view needs a field defined differently, not just hidden, override `fields_for`. `DraftRepository` gives its lists their own fields: ```rust /// A list shows the headline in capitals, and nothing else of a draft but its votes. fn fields_for(view: View) -> Vec> { if view.is_index() { return vec![ Field::new(Post::title) .label("headline") .resolve(|title, _post| Value::from(title.as_str().unwrap_or_default().to_uppercase())), Field::new(Post::votes), ]; } Self::fields() } ``` Searching, filtering and sorting always read `fields`, whatever `fields_for` returns. ## How each type is written A field writes its column's type the way Restify for PHP writes it, so a client of either reads the same JSON. | Column type | JSON | Example | | --- | --- | --- | | `String`, `Uuid`, `Ulid` | A string | `"Hello"` | | Integers | A number | `10` | | `f32`, `f64` | A number | `4.5` | | `bool` | `true` or `false`. With `.as_integer()`, `1` or `0` | `false` | | `Timestamp` | UTC with six decimals of the second | `"2026-01-03T12:30:00.000000Z"` | | `laravel::time::civil::Date`, for a `date` column | The day | `"2026-11-20"` | | `Decimal` | A string, so no digit is lost. With `.decimals(2)`, exactly two decimals | `"4.50"` | | `Option` | `null`, or as `T` | `null` | | `serde_json::Value`, `Vec` | As serde writes it | `["a", "b"]` | A `date` column holds a day and no time, so read it as `laravel::time::civil::Date`, as the example app's [`Milestone`](https://github.com/BinarCode/laravel-restify-rust/blob/main/example/src/models/milestone.rs) does. This works on SQLite, PostgreSQL, MySQL and MariaDB. The OpenAPI document and the MCP tools describe it as a string with `"format": "date"`. Restify for PHP shows a column with Eloquent's `date` cast as midnight UTC, such as `"2026-11-20T00:00:00.000000Z"`. To show that, add `.resolve(|day, _| match day { Value::String(day) => Value::String(format!("{day}T00:00:00.000000Z")), other => other })` to the field. `.as_integer()` is for a boolean column that the PHP application's model doesn't cast to `boolean`: on SQLite and MySQL, Restify for PHP then shows the `0` or `1` the database returns. The answer to a create or an update shows the value as sent, such as `true`, because Restify for PHP answers with the model it just filled. To show a column of another type, such as an enum, implement `restify::Property` for it. Its `property` is the type's JSON Schema. Its `wire` writes the value and defaults to what serde writes. ## Mistakes the application refuses to start with Restify checks every repository's fields when the application starts, and names the repository, the field and the fix: - Two fields of one view have the same name. Remove one, or rename one with `label`. - A computed field is marked `searchable`, `matchable` or `sortable`. It has no column to query. - A field is marked `matchable` or `matchable_as` but its column's type can't read a filter's value, such as `serde_json::Value`. Set `Property::MATCH` and `Property::parse` for the type, or write a [scope](filtering.md#scopes). Every integer type, `String`, `Uuid`, `Ulid`, `f64`, `Decimal`, `bool`, `Timestamp` and `civil::Date` can be read. --- # 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> { 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> { 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::().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> { 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, value: &Value, rest: &Map) -> Builder { 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::().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::() .global_search::() ``` ```rust impl GlobalSearch for PostRepository { const RESULTS: u64 = 3; fn title(post: &Post) -> String { post.title.clone() } fn subtitle(post: &Post) -> Option { 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). --- # Relationships - [Introduction](#introduction) - [Declaring the relationships clients may load](#declaring-the-relationships-clients-may-load) - [Loading relationships](#loading-relationships) - [What a response contains](#what-a-response-contains) - [The order of a list](#the-order-of-a-list) - [Nested relationships](#nested-relationships) - [Picking columns](#picking-columns) - [Limiting lists with relatablePerPage](#limiting-lists-with-relatableperpage) - [Who can see a relationship](#who-can-see-a-relationship) - [Raw relationships and the model's JSON](#raw-relationships-and-the-models-json) - [Many-to-many relationships clients can change](#many-to-many-relationships-clients-can-change) - [Attach, detach and sync](#attach-detach-and-sync) - [Who may attach, detach and sync](#who-may-attach-detach-and-sync) - [Nested routes](#nested-routes) ## Introduction A post has an author and comments. With `?related=`, a client gets them in the same response as the post, instead of making one request per post: ``` GET /api/restify/posts?related=user,comments ``` Restify loads only the relationships the repository lists. It loads each one with one query for the whole page, as the framework's `with` does, so a list of 15 posts with their authors runs two queries, not sixteen. The request and the response are the same as Restify for PHP's, so a client of a PHP application keeps working. ## Declaring the relationships clients may load First declare the relationships on the model, as the framework's [model relationships](https://github.com/laravel/rust-framework/blob/0.x/docs/model-relationships.md) guide shows: ```rust #[model] pub struct Post { pub id: i64, pub user_id: i64, pub title: String, // ... #[belongs_to] pub user: BelongsTo, #[has_many] pub comments: HasMany, #[belongs_to_many] pub tags: BelongsToMany, } ``` Then list the ones clients may load in the repository's `related` method: ```rust use restify::{Related, Repository}; impl Repository for PostRepository { // ... fn related() -> Vec> { vec![ Related::through::(Post::user, |post| &post.user), Related::through::(Post::comments, |post| &post.comments), Related::raw(Post::tags), ] } } ``` There are two ways to show a relationship: | Declaration | Shows each related model as | Restify for PHP | | --- | --- | --- | | `Related::through::(Post::user, \|post\| &post.user)` | A resource of the related repository: its list fields, its policy, its own relationships | `BelongsTo::make('user', UserRepository::class)`, `HasMany`, `HasOne`, `BelongsToMany` | | `Related::raw(Post::tags)` | The related model's own JSON, as its `Serialize` writes it | A string in `related()`, such as `'tags'` | Prefer `through`: it shows only what the related repository shows, to whom it shows it. `through` takes the relationship and a closure that returns the model's field for it, because the framework has no other way to read a loaded relationship. Every kind of relationship works with both, except `#[morph_to]`. A client names a relationship by its field's name: `user`, `comments`, `tags`. A repository without a `related` method lets clients load nothing. ## Loading relationships | Request | Loads | | --- | --- | | `GET /api/restify/posts?related=user` | Each post's author | | `GET /api/restify/posts?related=user,comments` | Each post's author and comments | | `GET /api/restify/posts/1?related=comments` | One post's comments | | `GET /api/restify/posts/1?include=comments` | The same: `include` is another name for `related` | - When a request sends both `related` and `include`, only `related` is read. - A name the repository doesn't list is ignored, as Restify for PHP ignores it. The request still answers `200`. - `?related=` works with every other list parameter, such as `?search=`, filters, `?sort=` and `?page=`. Create, update and delete don't take it. The `posts-index-tool` and `posts-show-tool` MCP tools take the same thing as an `include` argument, as in Restify for PHP: a comma-separated string, such as `"user,comments"`. The argument's description lists the names the repository allows, so an agent knows what it may ask for. An MCP tool leaves out a relationship whose repository doesn't set `const MCP`. See [MCP](mcp.md). ## What a response contains Each loaded relationship goes under the resource's `relationships` key, named as the client asked for it. It is never in `attributes`. ```json { "data": { "id": "1", "type": "posts", "attributes": { "user_id": 1, "title": "Laravel for Rust", "votes": 10 }, "relationships": { "user": { "id": "1", "type": "users", "attributes": { "name": "Ada Admin", "is_admin": true } }, "comments": [ { "id": "1", "type": "comments", "attributes": { "post_id": 1, "body": "Great read" } } ], "tags": [ { "id": 1, "name": "rust", "created_at": "2026-01-01T09:00:00.000000Z", "pivot": { "post_id": 1, "tag_id": 1, "position": 2 } } ] } } } ``` - A `through` relationship shows each related model as a resource of the related repository: `id`, `type`, and the repository's **list** fields as `attributes`, even when the parent is shown on its own. A related resource has no `meta`. - A `raw` relationship shows the related model's JSON. See [Raw relationships and the model's JSON](#raw-relationships-and-the-models-json). - A belongs-to or has-one relationship is one object, or `null` when there is no related row. - A has-many or belongs-to-many relationship is a list, empty when there are no related rows. See [The order of a list](#the-order-of-a-list). - A resource has a `relationships` key only when the request loads at least one relationship. ## The order of a list PHP loads a relationship without `ORDER BY`, so it shows the rows in whatever order the database reads them. On SQLite and MySQL that order follows the indexes. Restify sorts by the same columns, so every database, PostgreSQL included, shows what PHP shows: | Relationship | Order | | --- | --- | | Has-many, has-one-of-many, through | The related models' keys | | Many-to-many, when the join table has an index that starts with the parent's column, such as `unique(['post_id', 'tag_id'])` for a post's tags | That index's other columns (`tag_id`), then the join table's key | | Many-to-many without such an index, such as a `label_task` with only an `id` | The join table's key: the order the rows were attached in | | Many-to-many whose join table has neither | The related models' keys | The first request that loads a many-to-many reads its join table's indexes once, and keeps the answer until the application stops. If a migration changes those indexes, restart the application. ## Nested relationships A dot loads the related repository's own relationships into each related model: ``` GET /api/restify/posts/1?related=comments.user ``` Each comment then has its own `relationships` key with its author. The names after the dot are those the related repository lists: `comments.user` works because `CommentRepository::related` lists `user`. Nesting works only through `through`: on a `raw` relationship, such as `?related=post.user` on a comment, the part after the dot is ignored and the post is shown without its author. Restify for PHP differs on one point. On a **list**, such as `GET /comments?related=post.user`, PHP does load the author and puts it inside the raw post's JSON. Restify for Rust can't: the framework loads a relationship only through its typed method, such as `Post::user`, never from a name read in the URL. To get nested relationships, show the relationship with `through`. ### How deep, and how many A request may go at most 3 relationships deep, such as `posts.comments.user`, and name at most 20 relationships in all, counting each one inside another: `comments.user,tags` names three. A request that asks for more answers `422`, and the message names the limit: ```json { "message": "`user.posts.user.posts` goes 4 relationships deep, and at most 3 are allowed. Ask for the deeper relationships in another request, starting from the related repository. The limit is `RESTIFY_RELATED_MAX_DEPTH`.", "errors": { "related": ["`user.posts.user.posts` goes 4 relationships deep, and at most 3 are allowed. ..."] } } ``` The error names `include` when the client sent `include`. An MCP tool's `include` argument has the same limits. | Setting | Environment variable | Default | | --- | --- | --- | | `related_max_depth` | `RESTIFY_RELATED_MAX_DEPTH` | `3` | | `related_max_paths` | `RESTIFY_RELATED_MAX_PATHS` | `20` | `0` turns a limit off. Restify for PHP has no limits. Without them, two repositories that relate to each other, such as users and posts, let one request load the same rows again at every level, so the answer grows with each level. Every recorded PHP request stays within these limits. A name the repository doesn't list still counts toward the total, even though it is ignored. ## Picking columns `?related=user[name]` shows only the related resource's `name`. Separate several columns with `|`: `?related=comments[body|user_id]`. Columns combine with nesting: `?include=posts[id|title].comments[body]`. - A related resource shows the fields whose column the client picked, and only those its repository shows. `comments[body|user_id]` shows `body` alone when the comments repository has no `user_id` field. - When one record is shown on its own, a related resource has no `id` unless the client picked the key column, such as `posts[id|title]`. A list keeps the `id`. Restify for PHP does the same, because it selects only the picked columns from the database in the first case. - A `raw` relationship ignores the columns and shows the whole model. ## Limiting lists with relatablePerPage `?relatablePerPage=5` loads at most 5 related models of each `through` relationship that holds a list, for each record. `?relatablePerPage[posts.comments]=5` limits one path only. - When one record is shown on its own, a list relationship is always limited, by default to the related repository's `RELATABLE_PER_PAGE`, which is 15. A many-to-many relationship declared with [`Related::many`](#many-to-many-relationships-clients-can-change) is the exception. It uses the default of the repository that shows it, as Restify for PHP's `BelongsToMany` field does. `TeamRepository` sets `RELATABLE_PER_PAGE = 2`, so `GET /teams/1?related=users` shows two members. - A list of records limits its relationships only when the request sends `relatablePerPage`, or the configuration sets `max_per_page`. Otherwise it loads every related model, as Restify for PHP does, and a recorded PHP answer depends on it. In production, set `RESTIFY_MAX_PER_PAGE`: it caps the page and turns this limit on for lists too. See [Before you go to production](production.md). - A value that isn't a positive number falls back to `RELATABLE_PER_PAGE`, and `max_per_page` caps it. - A `raw` relationship is never limited. ```rust impl Repository for CommentRepository { // ... const RELATABLE_PER_PAGE: u64 = 10; } ``` To load fewer related models whatever the request says, such as only approved comments, declare a filtered relationship on the model, like `#[has_many(filter = Comment::approved.eq(true))]`, and list that one instead. ## Who can see a relationship A `through` relationship asks the related repository, as Restify for PHP's relationship fields do: - A request that the related repository's `Action::AllowRestify` refuses doesn't get the relationship at all: it is left out of `relationships`, as if not asked for. - The related rows are only those the related repository's `Repository::query` lets the request reach, as on that repository's own endpoints. `query` gets `Action::Index` for a relationship that holds a list, and `Action::Show` for one that holds one model. A row that `query` hides is left out of a list, and a relationship that holds one model shows `null`. Restify for PHP doesn't apply the related repository's query here. - A related model that the related repository refuses to show, with `Action::Show`, is left out of a list. For a relationship that holds one model, the whole request answers `403`. - Each related resource shows the fields its repository shows to this request, so a field with `can_see(is_admin)` stays hidden from other users. - The related rows go through the related repository's soft-delete scope. A model whose PHP version uses `SoftDeletes` should also filter its relationships, such as `#[has_many(filter = Post::deleted_at.is_null())]`, because Eloquent leaves trashed rows out of every relationship. To let only some requests load a relationship, give it a gate. Other requests don't get it, as if they hadn't asked: ```rust Related::through::(Post::user, |post| &post.user).can_see(is_admin) ``` A `raw` relationship asks nobody: a client that may see the parent sees the related model's JSON. ## Raw relationships and the model's JSON `Related::raw` shows what the related model's `Serialize` writes, and nothing else decides it. So: - Mark the fields no client may see `#[serde(skip)]` on the model, as Laravel's `$hidden` does. - A many-to-many relationship adds a `pivot` to each model, as Laravel does: the join table's two key columns, such as `post_id` and `tag_id`, and the columns of the join row, which the framework would write under `join`. - To write the same JSON as a PHP application, give the model's fields `#[serde(serialize_with = "..")]`. The example app's `models/php.rs` writes timestamps as Eloquent does (`2026-01-02T09:00:00.000000Z`, through `restify::Property::wire`), a `decimal:2` column as `"4.50"`, and an uncast boolean as `0` or `1`. ## Many-to-many relationships clients can change `Related::many` shows a many-to-many relationship the same way `through` does. It also lets clients add and remove related models, with the endpoints in the next section. It works with `#[belongs_to_many]`, `#[morph_to_many]` and `#[morphed_by_many]`. It is the Rust version of Restify for PHP's `BelongsToMany` and `MorphToMany` fields. For example, a team has members, and each member has a role. The role is stored in the join table `team_user`: ```rust #[model] pub struct Team { pub id: i64, pub name: String, // ... #[belongs_to_many] pub users: BelongsToMany, #[morph_to_many(Tagging::taggable)] pub tags: MorphToMany, } /// A row of `team_user`: the member's role on the team. #[join_row] pub struct TeamUser { /// `owner` or `member`. The column's default is `member`. #[default] pub role: String, } ``` The repository lists both relationships with `Related::many`: ```rust use laravel::validation::Rule; use restify::{Pivot, Related}; fn related() -> Vec> { vec![ Related::many::(Team::users, |team| &team.users) .pivot(Pivot::new(TeamUser::role).rules([Rule::required(), Rule::one_of(["owner", "member"])])), Related::many::(Team::tags, |team| &team.tags), ] } ``` `pivot` names a column of the join row. It does two things: - Each related resource shows the column under `pivots`, such as `"pivots": { "role": "owner" }`. - An attach reads the column from the request and checks it with its rules. With `Rule::required()`, every attach must send it. Things to know: - To show a pivot, the field's type must name the join row, such as `BelongsToMany`. If it doesn't, the application refuses to start and says why. - A sync never writes pivot columns. So a join column that has to be filled, like `role`, needs `#[default]` on the join row, and a default in the database. - `Related::many` on a relationship that isn't many-to-many doesn't compile. Use `through` for the others. ## Attach, detach and sync | Request | What it does | Answer | | --- | --- | --- | | `POST /api/restify/teams/1/attach/users` with `{"users": [2, 3], "role": "member"}` | Adds users 2 and 3 to team 1, each with the role sent | `201` with the new join rows | | `POST /api/restify/teams/1/detach/users` with `{"users": [2]}` | Removes user 2 from team 1 | `204` with no body | | `POST /api/restify/teams/1/sync/users` with `{"users": [1, 3]}` | Makes users 1 and 3 the only members | `200` with `[]` | The URL ends with the relationship's name, and the body sends the keys under that same name. One key on its own works too, such as `{"users": 3}`. A key may be a number or a string. An attach answers with each new join row, as Restify for PHP does: ```json { "data": [ { "team_id": 2, "user_id": 3, "role": "member" } ] } ``` For a polymorphic relationship, each row also has the type column, such as `"taggable_type": "team"`. What can go wrong: | Answer | When | | --- | --- | | `404` | No team has the key in the URL, or no user has one of the keys sent. A detach also finds soft-deleted users. | | `400` | The repository has no `Related::many` with that name. Or the request may not use the related repository, because its `Action::AllowRestify` refuses. Or the relationship's `can_see` refuses. | | `422` | A key is neither a number nor a string, or a pivot breaks its rules. Or an attach names a user who is already a member, or names one user twice: the error is under the relationship's name, such as `{"users": ["User 3 is already attached to this Team. Leave it out, or detach it first."]}`, and nothing is written. | | `403` | The team's repository refuses the change. See the next section. | Restify for PHP inserts the join row of an attach without checking, so attaching a member again answers its database's error, a `500`, when the join table has a unique index, and adds a second row when it hasn't. Restify for Rust answers the `422` above instead, whether the table has the index or not. Keep the unique index anyway: two attaches at the same moment can both pass the check, and the index stops the second. Two details match Restify for PHP on purpose: - Detaching a user who isn't a member still answers `204`. - A sync only writes keys. Members who stay keep their role. New members get the column's default. ## Who may attach, detach and sync Each change asks the parent's repository in `authorize`, with the relationship's name: | Request | Question asked | How often | | --- | --- | --- | | attach | `Action::Attach("users")` | Once for each user sent | | detach | `Action::Detach("users")` | Once for each user sent | | sync | `Action::Sync("users")` | Once, for all the users | The model that `authorize` gets is the team. To see which users the change is about, call `restify::relating::(request)`. During an attach or a detach, it holds one user. During a sync, it holds all of them. The users are looked up through the related repository, here `UserRepository`, the same way its own show endpoint finds a row. That means its `Repository::query` is applied, for `Action::Show`. So a user that `query` hides counts as missing, just like an id that no user has. The permission is asked about the users that were found before missing ids are reported. So when a request names a user it may not attach and an id that doesn't exist, it gets `403`, and doesn't learn which of its ids exist. Restify for PHP looks every id up first, so it answers `404` before it asks the policy. When no id was found at all, the answer is `404`, as in PHP. That `404` tells nothing hidden, because only users that `query` lets the request reach count as found. This example lets any user add themselves to a team, while only an admin may add other people: ```rust async fn authorize(action: Action, request: &Request, _team: Option<&Team>) -> laravel::Result<()> { let allowed = match action { Action::AllowRestify | Action::Index | Action::Show | Action::Store => true, Action::Attach("users") => { let user: User = request.user().await?.or_abort(401)?; let joins_alone = restify::relating::(request) .iter() .all(|member| member.id == user.id); user.is_admin || joins_alone } Action::Update | Action::Delete | Action::Detach("users") | Action::Sync("users") | Action::Attach("tags") | Action::Detach("tags") => is_admin(request).await?, _ => false, }; if allowed { Ok(()) } else { Err(laravel::abort(403)) } } ``` A question that `authorize` doesn't handle reaches `_ => false`, so it is refused. Here, nobody may sync tags. Restify for PHP answers that case with "Missing method [syncTags] in your policy". Restify for Rust answers with its usual refusal. ## Nested routes Every relationship shown with `through` or `many` also gets routes under its parent. The URL uses the related repository's name, such as `comments`: | Request | What it does | | --- | --- | | `GET /api/restify/posts/1/comments` | Lists the comments of post 1. Search, filters, sorting and pages work as usual. | | `GET /api/restify/posts/1/comments/2` | Shows comment 2, if it belongs to post 1 | | `POST /api/restify/posts/1/comments` | Creates a comment on post 1. The posts repository must allow `Action::Update` on post 1. | | `PUT`, `POST` or `PATCH /api/restify/posts/1/comments/2` | Changes comment 2, if it belongs to post 1 | | `DELETE /api/restify/posts/1/comments/2` | Deletes comment 2, if it belongs to post 1 | The comments repository does the work, with its own fields, rules and `authorize`. The middleware of both repositories run: the posts repository's because the route is its own, and the comments repository's before the operation. See [Where the middleware run](repositories.md#where-the-middleware-run). `?related=` is different: it runs no middleware of the related repository. The parent adds four rules: - **Only the parent's rows exist.** A comment of another post answers `404`, as if it didn't exist. - **The parent must be visible.** The posts repository must allow `Action::Show` on the post, or the request answers `403`. - **A write changes the parent.** A create, an update or a delete also needs `Action::Update` on the post, or it answers `403`. This holds even when the comments repository allows the write: a user who may comment but may not edit the post can't use `POST /posts/1/comments`. If the comments input has a `post_id` field, such a user can create with `POST /api/restify/comments` instead. - **A new record belongs to the parent.** Restify puts the post's key into the input as `post_id`, so the comments' own rules see it. If the request sends a different `post_id`, it answers `422` with "The post_id must match the parent in the URL.". A create answers `201`, and its `Location` header holds the new comment's own path, such as `/api/restify/comments/6`. Creating through the parent works for `#[has_many]`, `#[has_one]`, `#[morph_many]` and `#[morph_one]`: - Through a polymorphic relationship, such as `POST /teams/1/notes`, Restify also sets the type column. - For a has-many relationship, the related model must declare the `#[belongs_to]` back to the parent. That's how Restify knows which column holds the parent's key. - Through a many-to-many relationship, a create answers `400`. Use attach instead. When the parent's repository doesn't show the relationship through a repository, the request answers `403` with "Eager field missing from the parent [posts] related fields.". The same happens when the request may not use the relationship. A `raw` relationship has no nested routes. The nested routes and attach, detach and sync are HTTP endpoints only. They have no MCP tools, because Restify for PHP has none. --- # Writing - [Introduction](#introduction) - [The create input](#the-create-input) - [The update input](#the-update-input) - [A unique value on update](#a-unique-value-on-update) - [Describing fields for AI agents](#describing-fields-for-ai-agents) - [Setting columns the client can't](#setting-columns-the-client-cant) - [Fields only some users may write](#fields-only-some-users-may-write) - [Dates from Restify for PHP clients](#dates-from-restify-for-php-clients) - [After a write](#after-a-write) - [Field types](#field-types) ## Introduction A repository names two input structs: `Store` for creating a model and `Update` for changing one. They are the framework's own fill structs, so they validate the input and decide which columns a client can write. Restify adds one thing: `#[derive(Schema)]`, which describes the struct to AI agents. A client can only write the fields these structs declare. A `POST` with `"is_admin": true` changes nothing unless `Store` has an `is_admin` field. ## The create input ```rust use laravel::prelude::*; use restify::Schema; /// What a client sends to create a post. Only these fields can be written. #[laravel::input(fills = Post)] #[validate(authenticated)] #[derive(Schema)] pub struct NewPost { /// The post's headline. #[validate(required.message("A post needs a title."), max_length(255))] pub title: String, /// The post's text. pub body: Option, #[validate(min_value(0))] pub votes: Sometimes, /// Whether the post is featured. Only an admin may set it: see the field's `can_store`. pub featured: Sometimes, /// Readers' average rating, from 0 to 10. #[validate(between(0, 10), invalid = "The :attribute field must be a number.")] pub rating: Option, /// When the post was published. `creating` sets the column. #[fill(skip)] #[validate(invalid = "The :attribute field must be a valid date.")] pub published_at: Option, } ``` - `#[laravel::input(fills = Post)]` makes the struct fill a `Post` and validate its fields. See the framework's `validation.md` and `models.md` guides for every rule and attribute. - `#[validate(authenticated)]` lets any logged-in user submit it. Use `#[validate(anyone)]` when guests may. The framework requires one of them. - A field that isn't an `Option`, a `Sometimes` or `#[serde(default)]` is required. - `published_at` is explained in [Dates from Restify for PHP clients](#dates-from-restify-for-php-clients). `POST /api/restify/posts` with this input answers `201`. The `Location` header holds the new post's path, such as `/api/restify/posts/9`, and the body holds the new post with the fields a list shows. Invalid input answers `422` with a message for each field, and the top-level `message` is the first of them, followed by "(and 2 more errors)" when there are more. The answer shows what the request sent, as Restify for PHP does: a column the input could have set but the request left out shows `null`, even when the database filled in a default. A field with `.default(..)` shows that value instead, as it does everywhere. Read the post again with `GET` to see the stored values. ## The update input ```rust use laravel::validation::Sometimes; /// What a client sends to change a post. `PATCH` changes the fields it sends; `PUT` must also send /// the title. #[laravel::input(fills = Post)] #[validate(authenticated)] #[derive(Schema)] pub struct EditPost { /// The post's headline. #[validate(required.message("A post needs a title."), max_length(255))] pub title: Sometimes, /// The post's text. Send `null` to clear it. pub body: Sometimes>, #[validate(min_value(0))] pub votes: Sometimes, // `featured`, `rating` and `published_at` as in `NewPost`, each in a `Sometimes`. } ``` Declare every field of an update as `Sometimes`. A field the request leaves out then keeps its value. With `Sometimes>`, an explicit `null` clears the column. The three update routes differ in which rules they check, as in Restify for PHP: | Request | Checks | | --- | --- | | `PATCH /api/restify/posts/1` | The rules of the fields the request sends. `{"votes": 11}` changes only `votes`. | | `PUT /api/restify/posts/1` | Every field's rules. A field marked `required` must be sent, so `{"votes": 11}` answers `422` with "A post needs a title." | | `POST /api/restify/posts/1` | The same as `PUT`. | A field left out of a `PUT` still keeps its value when no rule requires it. The MCP `posts-update-tool` updates like `PUT`, as in Restify for PHP, so its schema marks `title` as required. ### A unique value on update A `unique` rule on an update input must skip the record being changed, or the record can't keep its own value: renaming a milestone to its current title would fail with "The title has already been taken.". `restify::updating::(request)` is the record an update changes, and `None` for a create. Read it in the input's `rules` function, and give its key to `ignore`. This is the example app's `EditMilestone`: ```rust use laravel::validation::{DatabaseRules, Rule, Rules, Sometimes, ValidatesRequest}; /// What a client sends to change a milestone. #[laravel::input(fills = Milestone)] #[derive(Schema)] pub struct EditMilestone { /// The milestone's title, which no other milestone has. #[validate(required, max_length(255))] pub title: Sometimes, } impl ValidatesRequest for EditMilestone { async fn authorize(request: &Request) -> laravel::Result { request.authenticated().await } async fn rules(&self, request: &Request, rules: Rules) -> laravel::Result { let changed = restify::updating::(request).map(|milestone| milestone.id); Ok(rules.field("title", [Rule::unique(Milestone::title).ignore(changed)])) } } ``` The `rules` function replaces `#[validate(authenticated)]`, so `authorize` says who may send the input. This works for `PUT`, `PATCH`, the MCP update tool and each item of a bulk update. Restify's own route parameter is `{key}`, as in `/api/restify/milestones/{key}`. The framework's `unique(.., ignore = route("key"))` reads it, but only on the endpoints: an MCP tool has no URL, so the same rule fails there with a server error. Use `restify::updating` instead. ## Describing fields for AI agents `#[derive(Schema)]` builds the JSON Schema that the `posts-store-tool` and `posts-update-tool` MCP tools show an agent. It reads the struct at compile time: | In the struct | In the schema | | --- | --- | | The field's type | `type`: `string`, `integer`, `number`, `boolean`, `array` | | `Option` | The type or `null`, and not required | | `Sometimes` or `#[serde(default)]` | Not required | | A doc comment on the field | `description` | | `#[validate(max_length(255))]`, `min_length` | `maxLength`, `minLength` | | `#[validate(min_value(0))]`, `max_value` | `minimum`, `maximum` | | `#[validate(email)]`, `#[validate(url)]` | `format` | | `#[serde(rename = "..")]`, `#[serde(rename_all = "..")]` on the struct | The property's name | | `#[serde(skip)]` | Left out | Write a doc comment on every field. An agent decides what to send from those descriptions, so say what the field means and any rule the type doesn't show. A key the struct doesn't declare is ignored, by the endpoints and the MCP tools alike, as in Restify for PHP. The schema lists only the fields the struct declares, so an agent knows what it may send. ## Setting columns the client can't Some columns must come from the server: the owner of a new record, a tenant, a status. Set them in `creating` and `updating`, which run after the input has filled the write and before it runs. Each gets the write, the validated input and the request: ```rust use laravel::model::CreateBuilder; /// A new post belongs to the user who creates it, whatever the input says. async fn creating( create: CreateBuilder, _input: &NewPost, request: &Request, ) -> laravel::Result> { let user: User = request.user().await?.or_abort(401)?; Ok(create.set(Post::user_id, user.id)) } ``` `updating` has the same shape, with an `UpdateBuilder<'a, Post>` and the `Update` input. Both hooks may return an error to stop the write. The model's own hooks and events run as they do for any create or update. The input's fields must be `Clone`, because the input fills the write and is then lent to the hook. Every type `#[derive(Schema)]` knows is. ## Fields only some users may write A field's write gates decide who may set it. Each takes a gate, as `can_see` does: ```rust Field::new(Post::featured) .as_integer() .matchable() .can_see(is_admin) .can_store(is_admin) .can_update(is_admin), ``` | Gate | Asked by | | --- | --- | | `can_store` | A create, `POST /api/restify/posts`, and each item of a bulk create, `POST /api/restify/posts/bulk` | | `can_update` | A full update, `PUT` or `POST /api/restify/posts/1`, the MCP `posts-update-tool`, and each item of a bulk update, `POST /api/restify/posts/bulk/update` | | `can_patch` | A partial update, `PATCH /api/restify/posts/1` | | `readonly_when` | Every create and update, bulk ones included. When it passes, the field is ignored. | Restify checks them in Restify for PHP's order. It validates the whole input first, so an invalid value answers `422` even from a user who may not set the field. Then it drops the keys a gate refuses, and writes the rest. A refused key is not an error: the request succeeds without it. A bulk create or update asks the same gates as a single one. Restify for PHP asks a separate `canUpdateBulk` gate in bulk, and doesn't ask `canStore` or `canUpdate` there. So in PHP, a user allowed to use bulk could set a field that only admins may set. Restify for Rust doesn't copy that: a field closed to a user stays closed in bulk too. `can_update` doesn't stop a `PATCH`, as in Restify for PHP. A field that only an admin may change needs both `can_update` and `can_patch`. A gated field must be optional in the input, such as `Sometimes`, because a refused request continues without it. The application refuses to start otherwise; see [Troubleshooting](troubleshooting.md). ## Dates from Restify for PHP clients Clients written against Restify for PHP send dates in several forms, such as `2026-01-15`, `2026-01-15 10:00:00` and `2026-02-01T12:34:56.789+02:00`. The framework's `Timestamp` only reads the last. `restify::EloquentTimestamp` reads them all and stores them as Eloquent does: it keeps the clock time as written, drops the offset and the fraction of a second, and stores the result as UTC. So `2026-02-01T12:34:56.789+02:00` is stored as `2026-02-01T12:34:56Z`. A column is filled only from its own type, so skip the field when filling, and set the column in `creating` and `updating`: ```rust /// A new post belongs to the user who creates it, whatever the input says. async fn creating( create: CreateBuilder, input: &NewPost, request: &Request, ) -> laravel::Result> { let user: User = request.user().await?.or_abort(401)?; let published_at = input.published_at.map(EloquentTimestamp::timestamp); Ok(create.set(Post::user_id, user.id).set(Post::published_at, published_at)) } async fn updating<'a>( update: UpdateBuilder<'a, Post>, input: &EditPost, _request: &Request, ) -> laravel::Result> { Ok(match input.published_at { Sometimes::Present(published_at) => { update.set(Post::published_at, published_at.map(EloquentTimestamp::timestamp)) } Sometimes::Missing => update, }) } ``` A new client can use `Timestamp` and fill the column directly. ## After a write `stored`, `updated` and `deleted` run after the database has the change, with the model and the request. Use them for what follows a write, such as sending a notification. An error one returns becomes the response, but the write has already happened unless the request is a [bulk request](bulk.md), whose transaction it rolls back. ## Field types `#[derive(Schema)]` knows `String`, the integer and float types, `bool`, `Decimal`, `Uuid`, `Ulid`, `Timestamp`, `civil::Date`, `restify::EloquentTimestamp`, `laravel::hash::Password`, `serde_json::Value`, and `Vec`, `Option` and `Sometimes` of them. - A `civil::Date` takes a day, such as `2026-11-20`. Anything else, such as `2026-02-30` or `later`, fails validation with the field's `invalid` message. - A `Password` is a string clients send and no answer shows. Its schema says `"format": "password"` and `"writeOnly": true`. Filling a `PasswordHash` column from it hashes it. For another type, such as an enum, implement `restify::Property`: ```rust impl restify::Property for Status { fn property() -> serde_json::Value { serde_json::json!({ "type": "string", "enum": ["draft", "published"] }) } } ``` --- # Files and images - [Introduction](#introduction) - [Declaring a file field](#declaring-a-file-field) - [Sending a file](#sending-a-file) - [Where the file is stored](#where-the-file-is-stored) - [Keeping the file's name and size](#keeping-the-files-name-and-size) - [Showing the file](#showing-the-file) - [Replacing and deleting files](#replacing-and-deleting-files) - [Storing the file yourself](#storing-the-file-yourself) - [AI agents and bulk requests](#ai-agents-and-bulk-requests) - [Testing uploads](#testing-uploads) - [Differences from Restify for PHP](#differences-from-restify-for-php) ## Introduction A file field lets a client upload a file, such as a PDF or a profile photo, when it creates or updates a model. Restify saves the file on a disk of the framework's `laravel::storage`, and the model's column keeps the file's path on that disk. A response shows the path, or the file's URL. It works like the `File` and `Image` fields of Restify for PHP, with the same requests and answers. Two parts work together: - The **input struct** has a field of type `UploadedFile`. The framework reads the file from the request and checks its rules, such as "a PDF of at most 1 MB". - The **repository** lists `Field::file` or `Field::image` for the column. Restify saves the file and writes the column. Nothing is uploaded unless a repository declares both. ## Declaring a file field The column holds the file's path, so it is a nullable text column: `Option` in the model. ```rust #[model] pub struct Document { pub id: i64, pub title: String, pub attachment: Option, pub attachment_name: Option, pub attachment_size: Option, pub cover: Option, // .. } ``` The input struct gets a field with the column's name, of type `Sometimes`. Mark it `#[fill(skip)]`: the input can't write a file into a text column, the file field does that. Put the file's rules in `#[validate(..)]`: ```rust use laravel::http::UploadedFile; use laravel::validation::Sometimes; #[laravel::input(fills = Document)] #[validate(authenticated)] #[derive(Schema)] pub struct NewDocument { /// The document's title. #[validate(required)] pub title: String, /// A PDF of at most 1 KB. #[fill(skip)] #[validate(mimes("pdf"), max_kilobytes(1))] pub attachment: Sometimes, /// An image of at most 1 KB. #[fill(skip)] #[validate(image, max_kilobytes(1))] pub cover: Sometimes, } ``` Then list the field in the repository. `Field::file` shows the path; `Field::image` shows the image's URL: ```rust fn fields() -> Vec> { vec![ Field::new(Document::title), Field::file(Document::attachment) .path("documents") .store_original_name(Document::attachment_name) .store_size(Document::attachment_size) .prunable() .deletable(false), Field::new(Document::attachment_name), Field::new(Document::attachment_size), Field::image(Document::cover) .path("covers") .store_as("cover") .prunable(), ] } ``` This is the `DocumentRepository` of the example app: [`example/src/models/document.rs`](https://github.com/BinarCode/laravel-restify-rust/blob/main/example/src/models/document.rs) in the Restify for Rust repository. The framework's file rules are `file`, `image` (JPEG, PNG, GIF, BMP or WebP), `mimes("pdf", ..)`, `extensions("pdf", ..)`, `min_kilobytes(n)` and `max_kilobytes(n)`. `image` and `mimes` look at the file's bytes, not at its name, so a PDF named `cover.png` is not an image. The framework's [validation guide](https://github.com/laravel/rust-framework/tree/0.x/docs) lists them all. A file method, such as `.path(..)`, on a field made with `Field::new` is a mistake: the application refuses to start and names the field. ## Sending a file A client sends files in a `multipart/form-data` body, the body an HTML form with `enctype="multipart/form-data"` sends. The other fields go in the same form: ```shell curl -X POST https://example.com/api/restify/documents \ -H "Authorization: Bearer $TOKEN" -H "Accept: application/json" \ -F title=Report -F attachment=@report.pdf ``` | Request | With files | | --- | --- | | `POST /api/restify/documents` | Creates the model and saves the files. | | `PUT /api/restify/documents/1` | Updates the model and saves the files. | | `POST /api/restify/documents/1` | The same as `PUT`. Browsers' forms can only send `POST`, so this is the usual way. | | `PATCH /api/restify/documents/1` | Changes nothing. `PATCH` reads a JSON body only, as in Restify for PHP. | A JSON body still works for the other fields. A file field left out keeps its file. The framework refuses a request whose uploads are larger than 16 MB in all, before Restify sees it. Change the limit with the framework's `LimitUploads` middleware. ## Where the file is stored By default, a file field saves the file at the root of the `public` disk, under a random name of 40 letters and digits, such as `7kQ2…x9.pdf`. The extension comes from the file's bytes, so a renamed file gets its real extension. | Method | What it changes | Example | | --- | --- | --- | | `.disk("s3")` | The disk, one of `laravel::storage`'s. | `.disk("s3")` | | `.path("documents")` | The folder on the disk. | `documents/7kQ2…x9.pdf` | | `.store_as("cover")` | A fixed name instead of a random one. The extension that matches the file's content is added when the name doesn't already end with it. | A PNG image is saved as `covers/cover.png`, whatever the client named it | With `store_as`, every upload of every model gets the same name, so each upload replaces the last one. Use it for a file that exists once, such as a site's logo. The extension comes from the file's content, not from the name the client sent, the same way a random name gets its extension. So a client can't get a file saved as `.html` by naming it `cover.html`. A file whose type can't be told from its content gets no extension. Restify for PHP adds the extension of the client's file name instead. The disks are the framework's. The `public` disk keeps files in `storage/app/public` and serves them at `/storage`. See the framework's filesystem guide to add a disk such as S3. ## Keeping the file's name and size `store_original_name(column)` writes the name of the client's file, such as `report.pdf`, to another column on each upload. The column is `Option`. The name never holds a folder: a client that sends `../../secret.pdf` gets `secret.pdf`. `store_size(column)` writes the file's size in bytes. The column is `Option`. Neither column should be in the input struct: clients can't write them, only the upload can. ## Showing the file | Field | Shows | | --- | --- | | `Field::file(..)` | The path on the disk, such as `documents/7kQ2…x9.pdf`. | | `Field::file(..).url()` | The file's URL, such as `https://example.com/storage/documents/7kQ2…x9.pdf`. | | `Field::image(..)` | The image's URL while the file is on the disk, and `null` once it is gone, or the field's [`default`](fields.md). | A column that holds something the disk can't hold, such as a URL a PHP application stored, is shown as it is. ## Replacing and deleting files | What happens | Without `prunable()` | With `prunable()` | | --- | --- | --- | | A new upload replaces the file | The old file stays on the disk. | The old file is deleted. | | `DELETE /api/restify/documents/1` | The files stay. | The files are deleted after the record is. | | `DELETE /api/restify/documents/bulk/delete` | The files stay. | The files stay, as in Restify for PHP. | An old file is only deleted after the database write that stops pointing at it has succeeded. If that write fails, the file stays, so no row ever points at a missing file. At worst a file is left on the disk with no row pointing at it. Restify for PHP deletes the file first. A client can also delete one file and keep the model: ```shell curl -X DELETE https://example.com/api/restify/documents/1/field/cover \ -H "Authorization: Bearer $TOKEN" -H "Accept: application/json" ``` The request needs the `Update` permission, and the field's own write gates must let it write the field: its `can_update` and its `readonly_when`. A gate that refuses answers `403`. Restify then sets the column, and the name and size columns, to `null`, deletes the file, and answers `204`. A field that isn't a file field, or that says `.deletable(false)`, answers `404` with an empty message, as in Restify for PHP. A file field is deletable unless it says `.deletable(false)`, as in Restify for PHP. Restify for PHP only asks for the `Update` permission here, not the field's gates. So in PHP, a user who may not change a field could still delete its file. Restify for Rust asks the gates too. ## Storing the file yourself When the file needs more than a disk and a name, such as resizing an image first, save it in a hook. The hooks get the input, with its `UploadedFile`. Leave `Field::file` out, or use `Field::new` for the column, and set the column yourself: ```rust async fn creating( create: CreateBuilder, input: &NewDocument, _request: &Request, ) -> laravel::Result> { let Sometimes::Present(file) = &input.attachment else { return Ok(create); }; let path = file.store("documents").disk("public").await?; Ok(create.set(Document::attachment, path)) } ``` `updating` gets the `Update` input the same way. The framework's filesystem guide shows `store`, `store_as` and the rest. ## AI agents and bulk requests The MCP tools and the bulk endpoints take JSON, which can't hold a file. So: - The MCP `store` and `update` tools don't list file fields. A tool call that sends one anyway is refused with `422`, as a JSON body that sends text for a file is. Restify for PHP's store tool can fetch a file from a URL or a local path; Restify for Rust doesn't, because reading a URL or a path the agent chose is a way into the server's network and files. - A bulk create or update ignores file fields, as Restify for PHP does. - The OpenAPI document gives a create and a full update a `multipart/form-data` body next to the JSON one, with each file as `{"type": "string", "format": "binary"}`. ## Testing uploads Fake the disk at the start of the test, before anything uses it. The fake keeps files in a temporary folder that is removed when the test ends: ```rust use app::models::User; use laravel::http::client::Attachment; use laravel::storage; use laravel::testing::prelude::*; #[laravel::test] async fn an_upload_is_stored(app: Application) -> laravel::Result<()> { let disk = storage::fake("public")?; let taylor = User::factory().create().await?; let pdf = b"%PDF-1.4\n%%EOF\n".to_vec(); let created = app .post("/api/restify/documents") .acting_as(&taylor) .form(json!({ "title": "Report" })) .attach("attachment", Attachment::from_data(pdf, "report.pdf")) .await; created.assert_created(); let path = created.json()["data"]["attributes"]["attachment"] .as_str() .unwrap_or_default() .to_owned(); disk.assert_exists(&path).await; Ok(()) } ``` A form holds only text, so every value in `.form(json!({ .. }))` must be a string. A number makes the test panic with "the form body should serialize". Send it as a string, and the input reads it as its number type: ```rust .form(json!({ "milestone_id": milestone.id.to_string(), "title": "Design", "estimate": "2" })) ``` The example app's [`tests/files.rs`](https://github.com/BinarCode/laravel-restify-rust/blob/main/example/tests/files.rs), in the Restify for Rust repository, has the full tests: replacing, pruning, deleting one file and bulk deletes. ## Differences from Restify for PHP These are listed in the repository's [`oracle/divergences.json`](https://github.com/BinarCode/laravel-restify-rust/blob/main/oracle/divergences.json) too, with the recorded step that shows each one. - **A URL sent as text.** PHP's `File` field saves a URL sent instead of a file as it is. Here the input field is an `UploadedFile`, so text is refused with `422`, "The source field is invalid.". To accept URLs, add a plain text field with the `url` rule. - **`max:1` on a file field that gets text.** PHP measures the text and answers "must not be greater than 1 characters.". `max_kilobytes(1)` only measures files. - **A plain-text file's random name.** PHP adds the extension it guesses from the bytes, `txt` for plain text. The framework finds no extension in plain text, so the name has none. - **The `file` rule on a create.** PHP answers `500` to a create that sends a field whose rules include `file`: a PHP bug (`php-bug-file-rule-on-create`). Restify for Rust checks the rule and saves the file. - **Base64 files.** PHP's `Base64File` isn't served. Decode the text in a hook. Both applications must save files on the same disk while you move from PHP to Rust, so each finds the files the other saved. See [Migrating from Restify for PHP](migrating-from-php.md). --- # Actions and getters - [Introduction](#introduction) - [Writing an action](#writing-an-action) - [Actions on the list](#actions-on-the-list) - [Standalone actions](#standalone-actions) - [Who may see and run one](#who-may-see-and-run-one) - [What a handler answers](#what-a-handler-answers) - [Writing a getter](#writing-a-getter) - [Listing them in the repository](#listing-them-in-the-repository) - [The listings](#the-listings) - [Errors](#errors) - [The MCP tools](#the-mcp-tools) ## Introduction A repository's endpoints list, show, create, update and delete. Some operations are none of those, such as "publish these posts" or "count the posts". Write them as actions and getters. Restify serves each one at the same URLs as Restify for PHP, and as an MCP tool, with the same rules. - An **action** may write. It answers `POST`, and the client names it with `?action=`. - A **getter** only reads. It takes no input. It answers `GET`, and its name is the last part of the path. | | On the list | On one model | | --- | --- | --- | | Action | `POST /api/restify/posts/actions?action=publish-posts-action` | `POST /api/restify/posts/{id}/actions?action=publish-post-action` | | Getter | `GET /api/restify/posts/getters/stats` | `GET /api/restify/posts/{id}/getters/word-count` | `/action` works as well as `/actions` for running an action, as in PHP. `GET /api/restify/posts/actions` and its siblings list what a client may run: see [The listings](#the-listings). Both are written with one trait, `restify::CustomAction`, where `Post` is the repository's model. A repository serves none until it lists them, and each one refuses to run until its `can_run` method allows it. ## Writing an action An action is a type that implements `CustomAction`. This one publishes the post in the URL: ```rust use laravel::model::update; use laravel::prelude::*; use restify::{CustomAction, NoInput, Reply}; /// Publishes the post in the URL. pub struct PublishPostAction; impl CustomAction for PublishPostAction { const NAME: &'static str = "Publish Post Action"; type Target = Post; type Input = NoInput; async fn can_run(_request: &Request, _post: Option<&Post>) -> laravel::Result { Ok(true) } async fn handle(_input: NoInput, _request: &Request, mut post: Post) -> laravel::Result { update!(post { published_at: laravel::now() }).await?; Ok(Reply::message("Post published.")) } } ``` `POST /api/restify/posts/2/actions?action=publish-post-action` answers `{ "message": "Post published." }`. | Item | Required | Does | | --- | --- | --- | | `const NAME` | Yes | The name the listings show, such as `Publish Post Action`. PHP writes the class name in words, so use the PHP class name when you port an action | | `const DESCRIPTION` | No | What it does, for the listings and for AI agents. Write one: it's all an agent knows about the tool | | `const DESTRUCTIVE` | No | `true` for an action that destroys data, such as deleting. PHP's `DestructiveAction` | | `type Target` | Yes | What `handle` gets: `Post` for an action on one model, `Builder` for one on the list or a standalone one | | `type Input` | Yes | The input: a `#[laravel::input]` struct that derives `Schema`, or `NoInput` | | `fn uri_key` | No | The name in `?action=`. Defaults to `NAME` in kebab-case: `publish-post-action` | | `fn can_see` | No | Who sees it at all. Everyone by default | | `fn can_run` | In practice | Who may run it. Refuses everyone by default | | `fn handle` | Yes | Does the work and returns the answer | An input struct is written like a repository's `Store` struct: see [Writing](writing.md). It doesn't need `fills`, because `handle` decides what to write. It does need `#[validate(authenticated)]` or `#[validate(anyone)]`, like every input. This one takes a format: ```rust use restify::Schema; /// What a client sends to export the posts. #[laravel::input] #[validate(authenticated)] #[derive(Schema)] pub struct Export { /// The file format: `csv` or `json`. #[validate(required, one_of("csv", "json"))] pub format: String, } ``` Restify validates the input before it calls `handle`. A PHP action only validates when its `handle` calls `$request->validate(..)`, so a PHP action that never does accepts anything. ## Actions on the list An action on the list has `type Target = Builder`. The client sends the ids to run it on as `repositories`, or `"all"`: ```json { "repositories": [3, 5] } ``` `handle` gets the repository's query narrowed to those posts, newest key first, as PHP's `ActionRequest::builder` builds it. The query also has the request's own list parameters, such as `?search=` or a filter, next to `?action=`. Restify first asks `can_run` about each of those posts, and one refusal answers `403` before anything runs. The posts are read 200 at a time, like PHP's `Action::$chunkCount`, so `"all"` on a large table doesn't load the whole table into memory. Before any row is read, `can_see` is asked, so a hidden action loads nothing. `can_run` is never asked with `None` for an action on the list, because many actions refuse `None`, as this one does. To refuse a request before any row is read, use `can_see`. This one publishes the posts the user may update: ```rust use laravel::db::Builder; use serde_json::json; /// Publishes the posts listed in `repositories`. Each must be one the user may update. pub struct PublishPostsAction; impl CustomAction for PublishPostsAction { const NAME: &'static str = "Publish Posts Action"; type Target = Builder; type Input = NoInput; async fn can_run(request: &Request, post: Option<&Post>) -> laravel::Result { match post { Some(post) => request.can(PostPolicy::update, post).await, None => Ok(false), } } async fn handle(_input: NoInput, _request: &Request, posts: Builder) -> laravel::Result { let ids = posts.pluck(Post::id).await?; update!(Post::query().filter(Post::id.is_in(ids.clone())) { published_at: laravel::now(), }) .await?; Ok(Reply::data(json!({ "published": ids }))) } } ``` `POST /api/restify/posts/actions?action=publish-posts-action` with `{ "repositories": [3, 5] }` answers `{ "data": { "published": [5, 3] } }`. Without `repositories`, it answers `422` with "The repositories field is required." An id that isn't a post's key, or one the repository's `query` leaves out, is skipped. PHP runs a long list in chunks of 200 and calls `handle` once for each chunk. Restify calls `handle` once with the whole query. Every action runs in a database transaction, so an error in `handle` undoes what it wrote. ## Standalone actions A standalone action runs on no post in particular, such as an export. It has `type Target = Builder` and is listed with `Custom::standalone`. It takes no `repositories`, and it shows up both on the list and on one model, as in PHP. `handle` gets the repository's query, narrowed only by `Repository::query`. `can_run` is asked once, with `None`: ```rust /// Exports the titles of every post. It runs on no post in particular. pub struct ExportPostsAction; impl CustomAction for ExportPostsAction { const NAME: &'static str = "Export Posts Action"; type Target = Builder; type Input = Export; async fn can_run(_request: &Request, _post: Option<&Post>) -> laravel::Result { Ok(true) } async fn handle(input: Export, _request: &Request, posts: Builder) -> laravel::Result { let titles = posts.oldest(Post::id).pluck(Post::title).await?; Ok(Reply::data(json!({ "format": input.format, "titles": titles }))) } } ``` ## Who may see and run one Two methods decide, as PHP's `canSee` and `canRun` do: - `can_see(request)` decides whether the request sees the action at all. A hidden action is left out of the listings, and running it answers `403` with "You don't have permission to run this action." Everyone sees it by default. - `can_run(request, model)` decides whether the request may run it. The model is each post of `repositories` for an action on the list, the post in the URL for an action on one model, and `None` otherwise. A `false` answers `403` with "Not authorized to run this action." It refuses everyone by default, so write it for every action. This destructive action is for admins only: ```rust /// Deletes the posts listed in `repositories`. Only admins see it. pub struct ArchivePostsAction; impl CustomAction for ArchivePostsAction { const NAME: &'static str = "Archive Posts Action"; const DESTRUCTIVE: bool = true; type Target = Builder; type Input = NoInput; async fn can_see(request: &Request) -> laravel::Result { is_admin(request).await } async fn can_run(_request: &Request, _post: Option<&Post>) -> laravel::Result { Ok(true) } // ... } ``` `Repository::authorize` is asked for `Action::AllowRestify` first, as for every request to the repository. Nothing else of it is asked. In particular, the show policy of the post in the URL is not asked, as in PHP: a getter on one model also runs on a post the user can't see, if its `can_run` allows it. The post must still be in `Repository::query` for `Action::Show`. Safe setup: check the user in `can_run`, or keep the post out of `query` for that user. ## What a handler answers `handle` returns a `Reply`: a status and a JSON body. Its constructors are PHP's helpers: | PHP | Rust | Body | | --- | --- | --- | | `ok()` | `Reply::ok()` | `[]` | | `ok('Post published.')` | `Reply::message("Post published.")` | `{ "message": "Post published." }` | | `data($value)` | `Reply::data(value)` | `{ "data": value }` | | `response()->json($body)` | `Reply::json(body)` | `body` | Each answers `200`. Add `.status(StatusCode::ACCEPTED)` for another status. A model goes in as `serde_json::to_value(&post)?`. It isn't a JSON:API resource then: a `Post` comes back as `{ "id": 1, "title": "..", ... }`, without `type` and `attributes`. ## Writing a getter A getter is written the same way, with `type Input = NoInput`. It only reads, so don't write in its `handle`. A getter on the list gets the repository's query, and `can_run` is asked with `None`. This one counts the posts: ```rust /// Counts the posts, the published ones, and their votes. pub struct PostStatsGetter; impl CustomAction for PostStatsGetter { const NAME: &'static str = "Post Stats Getter"; type Target = Builder; type Input = NoInput; fn uri_key() -> String { "stats".to_owned() } async fn can_run(_request: &Request, _post: Option<&Post>) -> laravel::Result { Ok(true) } async fn handle(_input: NoInput, _request: &Request, posts: Builder) -> laravel::Result { let total = posts.count().await?; let published = posts.clone().filter(Post::published_at.is_not_null()).count().await?; let votes: Option = posts.sum(Post::votes).await?; Ok(Reply::json(json!({ "data": { "total": total, "published": published, "votes": votes.unwrap_or(0) }, }))) } } ``` `GET /api/restify/posts/getters/stats` answers `{ "data": { "total": 7, "published": 5, "votes": 95 } }`. A getter ignores the list parameters, so `?featured=true` changes nothing. A getter on one model has `type Target = Post`, like an action on one model. A getter with an input other than `NoInput` stops the application from starting, because a `GET` request has no body to send it in. Make it an action instead. ## Listing them in the repository A repository serves the actions it lists in `actions` and the getters it lists in `getters`. Where each one is listed decides which URLs run it: | Rust | PHP | Runs at | `Target` | | --- | --- | --- | --- | | `Custom::index_and_show::()` | Nothing: PHP's default | The list, where an action takes `repositories`, and one model | `Builder` | | `Custom::index::()` | `->onlyOnIndex()` | The list. An action takes `repositories` | `Builder` | | `Custom::show::()` | `->onlyOnShow()` | One model | `Post` | | `Custom::standalone::()` | `->standalone()` | The list and one model. No `repositories` | `Builder` | ```rust use restify::Custom; impl Repository for PostRepository { // ... fn actions() -> Vec> { vec![ Custom::index::(), Custom::show::(), Custom::standalone::(), Custom::index::(), ] } fn getters() -> Vec> { vec![ Custom::index::(), Custom::show::(), ] } } ``` `Custom::show` needs `type Target = Post`, and the others `type Target = Builder`. The compiler says so when they don't match. A PHP action or getter that calls none of `onlyOnIndex`, `onlyOnShow` and `standalone` is offered on the list and on each model. `Custom::index_and_show` does the same with one type. On the list it works like `Custom::index`. On one model, such as `POST /api/restify/posts/4/actions?action=publish`, it asks `can_run` about that post, and `handle` gets the query narrowed to it. Its MCP tool takes `repositories`, as PHP's tool does. `restify:import` writes `Custom::index_and_show` for such a PHP action. A getter in both places gets that narrowed query on one model too, such as `GET /api/restify/posts/4/getters/stats`. PHP's getter gets no query there, so when its `handle` counts with its own `Post::query()`, it counts every post on both URLs. To answer the same, start a new `Post::query()` in `handle` instead of counting with the query it gets. Keep small actions in the model's file, next to the repository. When there are several, move them to a file of their own, such as `src/models/post_actions.rs`, and re-export them from `src/models/mod.rs`. Each key must be kebab-case and unique among a repository's actions, and among its getters. Otherwise the application refuses to start and says which one to change. ## The listings Four `GET` requests list what a request sees, without what `can_see` hides: | Request | Lists | | --- | --- | | `GET /api/restify/posts/actions` | The actions on the list, those on the list and one model, and the standalone ones | | `GET /api/restify/posts/{id}/actions` | The actions on one model, those on the list and one model, and the standalone ones | | `GET /api/restify/posts/getters` | The getters on the list, and those on the list and one model | | `GET /api/restify/posts/{id}/getters` | The getters on one model, and those on the list and one model | With an `{id}`, a missing model answers `404`. An action is listed as PHP's `Action::jsonSerialize` writes it: ```json { "data": [ { "name": "Export Posts Action", "description": "", "destructive": false, "uriKey": "export-posts-action", "payload": { "format": ["required", "in:csv,json"] } } ] } ``` `payload` is the input's `#[validate(..)]` rules as Laravel writes them: `one_of` becomes `in`, `max_length` and `max_value` become `max`, `min_length` and `min_value` become `min`, and the others keep their names. A rule with its own message, such as `required.message("..")`, is listed by its name alone, `required`. It is `[]` when the input has no rules. A getter is listed as `{ "name": "Post Stats Getter", "uriKey": "stats" }`. ## Errors Restify runs the steps in PHP's order, and stops at the first that fails: | Status | Message | When | | --- | --- | --- | | `403` | The repository's | `Repository::authorize` refused `Action::AllowRestify` | | `404` | No query results for model .. | The URL has an `{id}` and no post has it, or the repository's `query` leaves it out | | `404` | `Action not found.` or `Getter not found.` | Nothing listed there has the key, or `?action=` is missing | | `403` | `You don't have permission to run this action.` (or `getter`) | `can_see` hides it | | `422` | `The repositories field is required.` | An action on the list without `repositories`. `null`, `""` and `[]` count as missing | | `403` | `Not authorized to run this action.` (or `getter`) | `can_run` refused one of the posts, or refused with `None` | | `422` | The input's | The input is invalid | ## The MCP tools When the repository's `const MCP` allows `actions` or `getters`, each one is a tool too. It is named after the repository, the key and the kind, as in Restify for PHP: `posts-publish-posts-action-action-tool`, `posts-export-posts-action-action-tool`, `posts-stats-getter-tool` and `posts-word-count-getter-tool`. - A tool on one model takes an `id`, next to the input's fields. - An action on the list takes the ids in `repositories`. Its schema asks for `resources`, as PHP's does, but the tool ignores that argument. - A getter's tool is marked `readOnlyHint`. An action's is marked `openWorldHint`, and `destructiveHint` is its `DESTRUCTIVE`: `true` or `false`. PHP leaves `destructiveHint` out, which agents read as `true`. - A user whose `can_see` refuses the action doesn't get its tool. The tool runs the same code as the endpoint. It returns `{ "success": true, "action": "publish-posts-action", "result": { ... } }`, with the body `handle` answered as `result`. When `can_run` refuses, it returns `{ "error": "...", "action": "publish-posts-action" }` instead. See [MCP](mcp.md#what-a-tool-returns). `laravel restify:list` shows each one with its endpoint and its tool. --- # Authorization - [Introduction](#introduction) - [Authenticating API tokens](#authenticating-api-tokens) - [Refusing some users everywhere](#refusing-some-users-everywhere) - [Deciding who may do what](#deciding-who-may-do-what) - [Using policies](#using-policies) - [What a refusal looks like](#what-a-refusal-looks-like) - [Rows a list leaves out](#rows-a-list-leaves-out) - [What the user may do with a record](#what-the-user-may-do-with-a-record) ## Introduction Two things protect a Restify API. A middleware decides who the request comes from, and each repository's `authorize` method decides what that user may do. The MCP tools go through both, exactly as the endpoints do. A repository refuses every request with `403` until it has an `authorize` method that allows `Action::AllowRestify` and the action itself. ## Authenticating API tokens Restify runs the middleware you give it before every endpoint and every MCP request. The framework's way to authenticate an API is a request guard, described in its `authentication.md` guide under "Stateless authentication". Restify ships one, `restify::auth::Sanctum`, which accepts the Laravel Sanctum tokens a PHP application already uses. The example app uses it in `src/lib.rs`: ```rust use laravel::auth::Authenticate; use restify::Restify; use restify::auth::Sanctum; providers.add(Sanctum::::new()); providers.add( Restify::new() .authenticate(Authenticate::via::>()) .repository::(), ); ``` Every endpoint and the MCP server now answer `401` without a valid token. [Sanctum tokens](sanctum.md) explains the guard, and [Authentication](authentication.md) the endpoints that log users in and give them tokens. Any other request guard works the same way. Give the authentication to `authenticate`, not to `middleware`. Both run before every endpoint, in the order you add them, but only `authenticate` is skipped by a [public repository](repositories.md#public-repositories). ## Refusing some users everywhere Restify for PHP checks a `viewRestify` gate on every request, after the authentication, and answers `401` "Unauthorized to view restify." when it refuses. Here, that gate is a middleware you add after `authenticate`. The example app refuses one user: ```rust #[middleware] pub async fn view_restify(request: Request, next: Next) -> laravel::Result { if request.authenticated().await? { let user: Option = request.user().await?; if user.is_some_and(|user| user.email == "mallory@example.com") { return Err(laravel::abort_with(401, "Unauthorized to view restify.")); } } Ok(next.run(request).await) } ``` ```rust Restify::new() .authenticate(Authenticate::via::>()) .middleware(view_restify) ``` The gate also runs on a public repository's routes, where every client is a guest, so it checks `request.authenticated()` before it reads the user. PHP's default gate lets nobody in outside the `local` environment, so a PHP application always defines its own; translate that one. ## Deciding who may do what `authorize` runs for every request, with the action and, when there is one, the model. This is the example app's `PostRepository`: ```rust async fn authorize(action: Action, request: &Request, post: Option<&Post>) -> laravel::Result<()> { match (action, post) { (Action::AllowRestify | Action::Index | Action::Store, _) => Ok(()), (Action::Show, Some(post)) => request.authorize(PostPolicy::show, post).await, (Action::Update, Some(post)) => request.authorize(PostPolicy::update, post).await, (Action::Delete, Some(post)) => request.authorize(PostPolicy::delete, post).await, (Action::StoreBulk | Action::UpdateBulk | Action::DeleteBulk, _) => { request.authorize(PostPolicy::bulk, ()).await } _ => Err(laravel::abort(403)), } } ``` | Action | Request | `model` is | | --- | --- | --- | | `Action::AllowRestify` | Every request to the repository, first | `None` | | `Action::Index` | `GET /posts`, `posts-index-tool` | `None` | | `Action::Show` | `GET /posts/{id}`, `posts-show-tool` | The model | | `Action::Store` | `POST /posts`, `posts-store-tool` | `None` | | `Action::Update` | `PUT` or `PATCH /posts/{id}`, `posts-update-tool` | The model, before the change | | `Action::Delete` | `DELETE /posts/{id}`, `posts-delete-tool` | The model | | `Action::StoreBulk` | `POST /posts/bulk` | `None` | | `Action::UpdateBulk` | `POST /posts/bulk/update` | Each model, before the change | | `Action::DeleteBulk` | `DELETE /posts/bulk/delete` | Each model | | `Action::Attach("users")` | `POST /teams/{id}/attach/users` | The team, once for each user | | `Action::Detach("users")` | `POST /teams/{id}/detach/users` | The team, once for each user | | `Action::Sync("users")` | `POST /teams/{id}/sync/users` | The team, once | `Action::AllowRestify` is whether the request may use the repository at all. Restify asks it before anything else, also before it looks for a model, so a request that fails it learns nothing of what the repository holds. A repository that doesn't allow it answers `403` to everything. The example app's tags are for admins alone: ```rust /// Only an admin may use the repository at all, and an admin may do everything. async fn authorize(action: Action, request: &Request, _tag: Option<&Tag>) -> laravel::Result<()> { match action { Action::AllowRestify if !is_admin(request).await? => Err(laravel::abort(403)), Action::AllowRestify | Action::Index | Action::Show | Action::Store | Action::Update | Action::Delete => { Ok(()) } _ => Err(laravel::abort(403)), } } ``` `Attach`, `Detach` and `Sync` name a relationship declared with `Related::many`. During those requests, `restify::relating::(request)` gives the users the change is about. See [Relationships](relationships.md#who-may-attach-detach-and-sync). The nested routes, such as `GET /posts/{id}/comments`, ask the parent's repository for `Action::Show` on the post, and also `Action::Update` for a create, an update or a delete. Then the comments repository is asked as for its own routes. See [Relationships](relationships.md#nested-routes). Later versions add actions, so end the `match` with `_ => Err(laravel::abort(403))`: what a repository doesn't name stays refused. Actions and getters are asked for `Action::AllowRestify` and nothing more of this method. Each one has its own `can_run`, which also refuses everything by default. See [Actions and getters](actions.md#who-may-see-and-run-one). Return `Ok(())` to allow the action, and an error to refuse it: `Err(laravel::abort(403))`. For show, update and delete, Restify finds the model first. A model that doesn't exist answers `404` before `authorize` runs for that action. To read the logged-in user, call `request.user()`: ```rust let user: User = request.user().await?.or_abort(401)?; ``` ## Using policies Keep the rules themselves in a policy, next to the model, and call it from `authorize` with `request.authorize`: ```rust use laravel::auth::policy; pub struct PostPolicy; #[policy] impl PostPolicy { /// An admin sees every post, an author sees their own, and everyone sees a published one. pub fn show(user: &User, post: &Post) -> bool { user.is_admin || user.id == post.user_id || post.published_at.is_some() } pub fn update(user: &User, post: &Post) -> bool { user.is_admin || user.id == post.user_id } pub fn delete(user: &User, post: &Post) -> bool { user.is_admin || (user.id == post.user_id && !post.featured) } /// Only an admin may create, change or delete many posts in one request. pub fn bulk(user: &User) -> bool { user.is_admin } } ``` A policy method without a model, such as `bulk`, is asked with `()`: `request.authorize(PostPolicy::bulk, ())`. `request.authorize` answers `403` when the policy says no, and for a guest. The framework's `authorization.md` guide covers policy responses, guests and administrators. ### A policy that reads the database A rule often needs another model, such as PHP's `$task->project->owner_id === $user->id`. Loading that model is a query, so the method is `async` and returns `laravel::Result`. Call it from `authorize` the same way: `request.authorize` waits for it. The example app's `TaskPolicy` reads the task's milestone: ```rust pub struct TaskPolicy; #[policy] impl TaskPolicy { /// Anyone may change a task until its milestone is past due. After that, only an admin may. /// It reads the milestone from the database, so it is `async`. The admin check comes first: /// an admin's request never loads the milestone. pub async fn update(user: &User, task: &Task) -> laravel::Result { if user.is_admin { return Ok(true); } let milestone = Milestone::find_or_fail(task.milestone_id).await?; Ok(milestone.due_on.is_none_or(|day| day >= laravel::time::today())) } } ``` When you translate a PHP policy, keep the order of its checks. PHP's `||` stops at the first `true`, so `$user->isAdmin() || $task->project->owner_id === $user->id` never loads the project for an admin. Return early the same way, before the query. Otherwise each row of a list runs a query that PHP never ran, because a list asks `Action::Show` about every row. An error from the method, such as a failed query, answers `500`, not `403`. See "Asynchronous checks" in the framework's `authorization.md`. ## What a refusal looks like A refusal is an error with the status `403`. Restify answers it with the message Restify for PHP gives for the question it asked, whatever message the repository's error had, because PHP's policies only say yes or no: | Question | Message | | --- | --- | | `Action::AllowRestify` | `Unauthorized to view repository posts. Check "allowRestify" policy.` | | `Action::Store` | `Unauthorized to store.` | | `Action::StoreBulk` | `Unauthorized to store bulk.` | | `Action::Attach` | `You cannot attach model:User, to the model:Team, check your permissions.`, with the related model's name and the repository's model's name | | `Action::Sync` | `You cannot sync key to the model:Team, check your permissions.` | | Any other | `This action is unauthorized.` | Where PHP's attach and sync messages name the model classes, such as `App\Models\Team`, Restify names the model, such as `Team`. An endpoint answers with the status and the message: ```json { "message": "This action is unauthorized." } ``` An MCP tool answers with a result the agent can read, not a protocol error. Its text is the message: ```json { "isError": true, "content": [{ "type": "text", "text": "This action is unauthorized." }] } ``` An error with another status, such as `laravel::abort(404)` to hide a record, keeps its own status and message. ## Rows a list leaves out A list asks `Action::Show` about each row of the page and leaves out the rows it refuses, as Restify for PHP does. It does this after the page is counted, so `meta.total` and `meta.to` still count those rows and a page may hold fewer rows than `per_page`. To keep rows out of the count as well, leave them out in `Repository::query`. See [Repositories](repositories.md). ## What the user may do with a record A shown record has a `meta` object that says what the request's user may do with it. Each flag is the answer of `authorize`: `true` when it allows the action, `false` when it refuses with `403`. ```json "meta": { "authorizedToShow": true, "authorizedToStore": true, "authorizedToUpdate": false, "authorizedToDelete": false } ``` A listed record has it only with `?withMeta=true`. Both defaults are settings: `RESTIFY_SERIALIZE_SHOW_META` (on) and `RESTIFY_SERIALIZE_INDEX_META` (off). The answer to a create or an update follows the list's setting, as in Restify for PHP. --- # Sanctum Tokens - [Introduction](#introduction) - [Enabling the feature](#enabling-the-feature) - [Protecting routes](#protecting-routes) - [Reading the token's abilities](#reading-the-tokens-abilities) - [Creating tokens](#creating-tokens) - [Settings](#settings) - [What a token costs](#what-a-token-costs) - [Remembering tokens](#remembering-tokens) - [What a migrated database needs](#what-a-migrated-database-needs) - [Many token requests on SQLite](#many-token-requests-on-sqlite) - [When a token is refused](#when-a-token-is-refused) - [Testing](#testing) - [Limits](#limits) ## Introduction Most Restify for PHP applications protect their API with `auth:sanctum`. Their clients hold Laravel Sanctum personal access tokens, such as `12|aBcD...`, stored as hashes in the `personal_access_tokens` table. `restify::auth::Sanctum` is a request guard that accepts those same tokens, from that same table. When you move an application from PHP to Rust and keep its database, every client stays logged in. Nothing has to be re-issued. It does what Sanctum 4.5's guard does for a bearer token. It also creates tokens in Sanctum's format, so PHP accepts the tokens Rust makes. The login, register and logout endpoints that hand them out are in [Authentication](authentication.md). ## Enabling the feature The guard is behind the `sanctum` Cargo feature: ```toml # Cargo.toml [dependencies] laravel-restify = { version = "0.2", features = ["sanctum"] } ``` The guard reads tokens from Sanctum's `personal_access_tokens` table. A database that came from PHP has it: see [What a migrated database needs](#what-a-migrated-database-needs). A new application creates it with the migration in [Authentication](authentication.md#the-tokens-table). ## Protecting routes Add the guard once as a provider. That registers it in the container and reads its [settings](#settings). Then give its middleware to Restify, as you would any request guard: ```rust // src/app.rs use laravel::auth::Authenticate; use restify::Restify; use restify::auth::Sanctum; use crate::models::{PostRepository, User}; Application::configure().with_providers(|providers| { providers.add(Sanctum::::new()); providers.add( Restify::new() .authenticate(Authenticate::via::>()) .repository::(), ); }) ``` `User` is your user model. It must derive `Authenticatable`, as the framework's `authentication.md` guide shows, and its key must be an integer, as in Sanctum's default migration. The same middleware protects your own routes too: ```rust route.authenticate(Authenticate::via::>()).group(|route| { route.get("/me", me); }); ``` When the token is accepted, `Authenticated`, `Auth` and `request.user()` give the token's user. When it is refused, the client gets `401` with `{"message": "Unauthenticated."}`, the same answer as in PHP. If you forget `providers.add(Sanctum::::new())`, the guard is missing from the container and every protected request fails with a server error. ## Reading the token's abilities A Sanctum token carries a list of abilities, such as `["posts:read"]`, or `["*"]` for everything. `AccessToken::current()` returns the token that authenticated the current request. Call it in a handler, a policy or a repository: ```rust use restify::auth::AccessToken; pub async fn me(Authenticated(user): Authenticated) -> Json { let token = AccessToken::current(); let can_write = token.as_ref().is_some_and(|token| token.can("posts:write")); Json(json!({ "id": user.id, "token": token, "can_write": can_write })) } ``` How PHP calls map to Rust: | PHP | Rust | | --- | --- | | `$user->tokenCan('posts:write')` | `AccessToken::current().is_some_and(\|token\| token.can("posts:write"))` | | `$user->tokenCant('posts:write')` | `AccessToken::current().is_none_or(\|token\| token.cant("posts:write"))` | | `$user->currentAccessToken()->id` | `AccessToken::current().map(\|token\| token.id)` | `AccessToken` has the token's `id`, `name` and `abilities`. It never holds the secret or its hash. `AccessToken::current()` is `None` when the Sanctum guard did not authenticate the request. That includes tests that log in with `acting_as`, because `acting_as` skips the guard. ## Creating tokens `create_token` does what PHP's `$user->createToken($name, $abilities, $expiresAt)` does. Resolve the guard from the container, then call it: ```rust use restify::auth::Sanctum; let sanctum = laravel::resolve::>().await?; let token = sanctum.create_token(&user, "cli", &["posts:read"], None).await?; ``` It returns the token to give the client, such as `7|aBcD...`. The format is Sanctum's: the row's id, `|`, then the secret, which is the `token_prefix`, 40 random letters and digits, and the CRC32 of those 40 in hex. The table stores only the SHA-256 of the secret, so nobody can read the token back later. Its `tokenable_type` is the first name the guard accepts: `App\Models\User` by default (see [below](#what-a-migrated-database-needs)). To revoke a token, call `delete` on it. `AccessToken::current()` gives the token of the current request, which is how logout works: ```rust if let Some(token) = AccessToken::current() { token.delete().await?; } ``` ## Settings The settings live in the `SanctumConfig` section. They use the names and defaults of PHP's `config/sanctum.php`, so a migrated application sets the same values. | Setting | Variable | Default | What it does | | --- | --- | --- | --- | | `expiration` | `SANCTUM_EXPIRATION`, in minutes | none | A token stops working this long after its `created_at`. None or `0` means no limit. | | `last_used_at` | none | `true` | An accepted request writes the time to the token's `last_used_at` and `updated_at`, unless `last_used_at` already holds the same second. So a token writes at most once a second. | | `token_prefix` | `SANCTUM_TOKEN_PREFIX` | empty | Text put before the secret of each token that [`create_token`](#creating-tokens) makes. | | `cache` | `SANCTUM_CACHE`, in seconds | none | The guard remembers an accepted token and its user this long, and skips the database. None or `0` reads them on every request. Sanctum has no such setting: see [Remembering tokens](#remembering-tokens). | `SANCTUM_EXPIRATION` is not in Sanctum's published config file, which sets `expiration` to `null`. If your PHP application set a number there, set the same number in the variable. You can also change a setting in `src/app.rs`: ```rust use laravel::time::ToSpan; use restify::auth::SanctumConfig; Application::configure().with_config(|config, _| { config.section_mut::().expiration = Some(60.minutes().into()); }) ``` A token's own `expires_at` column is always checked, whatever `expiration` says. A prefixed token that PHP made, such as `12|myapp_aBcD...`, needs no setting: PHP hashed the prefix with the secret, so it is checked like any other token. ## What a token costs One query on PostgreSQL and MySQL. The guard reads the token and its user together, by the token's id, then compares the secret's hash, checks the expiry, and at most once a second writes `last_used_at`. Sanctum for PHP reads the token and the user with two queries. The guard runs Sanctum's two queries in two cases. On SQLite, where a query is a function call and not a trip to a server, the joined query measured slower than the two. And when the user model has a connection of its own (`#[model(connection = "..")]`), because the tokens are on the default one. A trip to the database is what costs, not the hashing or the checks, which take about 3 microseconds together. So a request that otherwise runs one query, such as showing one record, answers about 1.6 times fewer requests with a token than without one. A page of 15 records answers about 10% fewer. The measurements and the reasoning are in the benchmark's [What a token costs, and why](https://github.com/BinarCode/laravel-restify-rust/blob/main/bench/README.md#what-a-token-costs-and-why). The connection pool's size (`DB_MAX_CONNECTIONS`, 10 by default) didn't change this in the benchmark: with 50 clients at once, a pool of 30 served as many requests as a pool of 10. Raise it when your requests wait for the database, not for the processor, such as when the database is on another machine. ## Remembering tokens By default the guard asks the database on every request, as Sanctum does. So a deleted token stops working at once, and a change to a user shows on the next request. You can trade that for speed. With `SANCTUM_CACHE=30`, the guard remembers each accepted token and its user for 30 seconds, in the memory of the process, and a request with a remembered token runs no query for it. In the benchmark, showing one record with a token then answered 9% to 16% fewer requests than without one, where it answers 37% to 45% fewer without the setting. ```ini # .env SANCTUM_CACHE=30 ``` Or in `src/app.rs`: ```rust use laravel::time::ToSpan; use restify::auth::SanctumConfig; Application::configure().with_config(|config, _| { config.section_mut::().cache = Some(30.seconds().into()); }) ``` What changes while a token is remembered, for up to the time you set: | What happens | Without `cache` | With `cache` | | --- | --- | --- | | A handler calls `AccessToken::delete`, or the client calls Restify's `POST /api/logout` | The token is refused at once | The same, in the process that ran it. Another process of the application keeps accepting the token until its own time for it passes | | The token's row is deleted another way: by SQL, by the PHP application, by deleting it through the query builder | Refused at once | Still accepted until the time passes | | The user's row changes, such as `is_admin`, or is deleted | Seen on the next request | Seen when the time passes | | The token's `abilities` change | Seen on the next request | Seen when the time passes | | The token passes its `expires_at`, or `expiration` | Refused at once | Refused at once: the guard checks both on every request | | `last_used_at` | Written at most once a second | The same, by each process | So the time you set is the longest a revoked token can keep working. Choose it as you would choose the lifetime of a short-lived access token. A token sent without its id (no `12|` in front) is never remembered. The guard remembers at most 10,000 tokens. When more than that are in use at once, the others are read from the database as before. ## Many token requests on SQLite SQLite lets one connection write at a time. With its default settings, a write also waits until every read has ended, and reads wait for the write. Whoever waits sleeps and tries again after 1, 2, 5, 10 and up to 100 milliseconds, so under many requests at once some wait far longer than the write they wait for. A token adds a read to every request, and a write once a second. Turn on SQLite's write-ahead log (WAL). Reads and the write then don't wait for each other, and a write costs less. Add `journal_mode=wal` to `DATABASE_URL` in `.env`, and in every environment that runs the application: ```ini DATABASE_URL=sqlite://database/database.sqlite?mode=rwc&journal_mode=wal ``` The framework applies it to every connection it opens to that file (its `database.md`, "SQLite"). It is a setting of the URL, not of Restify, because an application's own `src/config/database.rs` runs after every provider and sets the connections again: a provider couldn't keep it there. For a PHP application on SQLite, `restify:import` writes a task to add it. PostgreSQL and MySQL don't need it: they lock a row, not the whole database. To check that it is on, write one record, then ask the file: `sqlite3 database/database.sqlite "PRAGMA journal_mode"` answers `wal`. Measured with the benchmark, creating a record with a token, 10 clients at once: | Settings | Create a record | | --- | --- | | SQLite's defaults | 1,099 requests a second, p99 199 ms | | `journal_mode=wal` | 3,474 requests a second, p99 54 ms | Three things to know before you turn it on: - **The setting is stored in the database file.** A PHP application that opens the same file uses the log too from then on. That is safe: PHP's SQLite reads and writes such a file like any other. Every process that uses the file must run on the same machine, because the log doesn't work over a network file system. - **The database is three files.** Next to `app.sqlite`, SQLite keeps `app.sqlite-wal` and `app.sqlite-shm`. Don't back up the database by copying the one file while the application runs. Use `sqlite3 app.sqlite ".backup copy.sqlite"`, which writes a whole copy. - **The first connection switches the file.** That takes a moment in which nobody else uses the database. Start the application once while the PHP application is idle, or switch the file yourself with `sqlite3 app.sqlite "PRAGMA journal_mode = WAL"`. To go back, remove `journal_mode=wal` from the URL, stop the application, and run `sqlite3 app.sqlite "PRAGMA journal_mode = DELETE"`. With the log, `synchronous=normal` makes writes faster still. The database file can't be damaged by it, but the last writes before a power cut or an operating system crash may be lost. Add it to the URL only if that is acceptable: `?mode=rwc&journal_mode=wal&synchronous=normal`. A connection you build in `src/config/database.rs` from `SqliteConnectOptions` instead of a URL sets its own `journal_mode`. Why the log helps, with the measurements, is in the benchmark's [Writes on SQLite](https://github.com/BinarCode/laravel-restify-rust/blob/main/bench/README.md#writes-on-sqlite). ## What a migrated database needs The `personal_access_tokens` table, exactly as Sanctum's migration created it. The guard reads it with the query builder; there is no model to declare. The `tokenable_type` column must name your user model. PHP writes one of two things there: - The class name, such as `App\Models\User`. This is the default. - An alias, if the application maps its models with `Relation::morphMap` or `Relation::enforceMorphMap`, such as `user`. `Sanctum::::new()` accepts `App\Models\User` and the model's morph name, which is `user` for a model named `User` (the struct's name in snake case, or what `#[model(morph = "..")]` sets). Look at what your table contains: ```sql SELECT DISTINCT tokenable_type FROM personal_access_tokens; ``` If you see other values, list every one that means this model: ```rust providers.add(Sanctum::::new().tokenable_types(["App\\Models\\Account", "account"])); ``` The list replaces the defaults, and its first name is what new tokens store. If your PHP application maps users to an alias, put the alias first. Tokens whose `tokenable_type` is not in it are refused, so a token that belongs to another model can never log in as a user with the same id. ## When a token is refused The guard follows Sanctum's `Guard` and `PersonalAccessToken` step by step. A token is refused when: - There is no `Authorization: Bearer` header, or the token is empty or `0`. - The token has the form `id|secret`, and the id is not made only of digits, or the secret is empty or `0`. Everything after the first `|` is the secret, even another `|`. - No row matches. A token `id|secret` finds the row by id and compares the SHA-256 of the secret with the stored hash in constant time. A token without `|` finds the row by the SHA-256 of the whole token. - `expires_at` is in the past, or `expiration` minutes have passed since `created_at`. - `tokenable_type` is not one of the accepted names, or the user with id `tokenable_id` no longer exists. Sanctum finds the token first and its user second. On PostgreSQL and MySQL the guard reads both with one query, and refuses the same tokens. ## Testing To test as a logged-in user without a token, use the framework's `acting_as`. To test the token itself, store a row the way Sanctum does and send it with `token(..)`. This uses the `sha2` and `hex` crates: ```rust use laravel::db; use sha2::{Digest, Sha256}; let id: i64 = db::table("personal_access_tokens") .insert_get_id( db::values! { tokenable_type: "user", tokenable_id: user.id, name: "test", token: hex::encode(Sha256::digest("secret")), abilities: r#"["*"]"#, created_at: laravel::now().timestamp(), updated_at: laravel::now().timestamp(), }, "id", ) .await?; app.get("/api/me").header("accept", "application/json").token(&format!("{id}|secret")).await.assert_ok(); ``` The example app's [`tests/sanctum_guard.rs`](https://github.com/BinarCode/laravel-restify-rust/blob/main/example/tests/sanctum_guard.rs), in the Restify for Rust repository, tests every rule on this page, including tokens created by real PHP Sanctum. ## Limits - **Bearer tokens only.** Sanctum also logs in single-page apps through the `web` session (`sanctum.guard` and `stateful`). This guard doesn't. - **Integer keys.** `tokenable_id` must be an integer, as Sanctum's `morphs` column is. Applications that used `uuidMorphs` are not supported. - **No hooks.** Sanctum's `TokenAuthenticated` event, `Sanctum::getAccessTokenFromRequestUsing` and `Sanctum::authenticateAccessTokensUsing` have no counterpart. - **A token with no abilities** (`abilities` is `NULL`) is accepted and grants nothing. PHP fails with a server error when such a token's abilities are checked. - **Header parsing** is the framework's `request.bearer_token()`. It reads the first word as the scheme, where PHP looks for the last `Bearer ` in the header and stops at a comma. The two differ only for unusual headers, such as `Bearer a,b` or a token after two spaces. --- # Authentication - [Introduction](#introduction) - [Register, login and logout](#register-login-and-logout) - [The tokens table](#the-tokens-table) - [Forgot and reset password](#forgot-and-reset-password) - [Verifying emails](#verifying-emails) - [Changing the emails](#changing-the-emails) - [The profile](#the-profile) - [Fields and gates on guest routes](#fields-and-gates-on-guest-routes) - [Settings](#settings) ## Introduction Restify for PHP gives an application a register, login and logout API with `Route::restifyAuth()`, forgot and reset password, email verification, and a profile API for the logged-in user. This crate serves the same endpoints, with the same requests and answers, so a frontend keeps working after the move to Rust. Links that PHP emailed before the move keep working too. Each part is off until you turn it on. The login endpoints need the `sanctum` Cargo feature, because they hand out [Sanctum tokens](sanctum.md). The [OpenAPI document](openapi.md#what-the-document-contains) lists each part you turn on, with the bodies its endpoints accept. ## Register, login and logout Add the Sanctum guard as a provider, then call `auth` with the repository of your user model. This is the example app's `src/lib.rs`: ```rust use laravel::auth::Authenticate; use restify::Restify; use restify::auth::Sanctum; providers.add(Sanctum::::new()); let restify = Restify::new() .authenticate(Authenticate::via::>()) .auth::() .profile::() .repository::() .repository::(); ``` The user model must derive `Authenticatable` and have `name`, `email` and `password` columns, with an integer key. A new application also needs [the tokens table](#the-tokens-table). The routes sit directly under `/api`, outside Restify's prefix and middleware, so a guest can reach them: | Request | Body | Answer | | --- | --- | --- | | `POST /api/register` | `name`, `email`, `password`, `password_confirmation` | `200`, the new user and a token | | `POST /api/login` | `email`, `password` | `200`, the user and a token | | `POST /api/logout` | Nothing; needs the token | `200`, after deleting the token | A login or register answer is the user as its repository shows it, with no `data` wrapper, and the token in `meta`: ```json { "id": "2", "type": "users", "attributes": { "name": "Bob Writer", "is_admin": false, "email_verified_at": null, "created_at": "2026-01-01T10:00:00.000000Z" }, "meta": { "authorizedToShow": false, "authorizedToStore": false, "authorizedToUpdate": false, "authorizedToDelete": false, "token": "6|A7Ri79DuX5wxx8sqXmLkIMcwYwZBUCRObjOO2ptF9c670a19", "expires_in": null } } ``` The `authorizedTo*` flags of a login or register answer are always `false`, even for an admin, because Restify builds the answer as a guest sees it (see [Fields and gates on guest routes](#fields-and-gates-on-guest-routes)). Don't read permissions from them. Read them from the profile, `GET /api/restify/profile` with the new token, whose `meta` has the user's real flags, or from the user's own attributes, such as a role. Restify for PHP logs the user in first, so its flags are the user's. The rules are PHP's: - **Register** needs an email that is valid, at most 255 characters, and not in the users table yet, and a password of at least 6 characters with a matching `password_confirmation`. The email is stored in lower case. The password is hashed with bcrypt, which PHP verifies too. Register writes only `name`, `email`, `password` and the timestamps, so its answer shows every other column as `null`, such as `"is_admin": null`, even when the database gave it a default. A field with `.default(..)` shows that value instead of `null`: a `role` field declared `Field::new(User::role).default("member")` answers `"role": "member"`. PHP answers the same way, because its answer is the model it filled, and a field's `->default()` replaces a `null`. - **Login** finds the user by the exact email, or else by the email in lower case, and checks the password. A wrong email or password answers `401` with `{"message": "Invalid credentials."}`. An email no account has takes as long to answer as a wrong password, because a login for a missing account spends the time of a bcrypt hash too. So the time of an answer doesn't tell which emails have an account. - **Logout** deletes the token the request was sent with, so it stops working, and answers `200` with `{"message": "Successfully logged out."}`. The user's other tokens keep working. Restify for PHP deletes the token too, but then answers `500` with `{"message": "Server Error"}`, because of a bug in PHP. A client that ignored the status there works the same here. ### Too many tries Register and login use PHP's limits. Going over a limit answers `429 Too Many Requests`, with a `Retry-After` header that says how many seconds to wait. | Route | Limit | | --- | --- | | `POST /api/login` | 6 tries a minute for one email from one IP address, and 30 tries a minute from one IP address, whatever the email | | `POST /api/register` | 6 a minute from one IP address | Every try counts, whether it succeeds or not, as in PHP. The email counts in lower case. The limits use the framework's rate limiter (its `rate-limiting.md` guide), which keeps its counts in the default cache store. The `memory` store, used when `CACHE_STORE` is not set, keeps one count per process, and loses it on restart. With several servers, set `CACHE_STORE` to `database` or `redis`, so that they share one count. Two small differences from PHP: - PHP refills a limit all at once when its minute ends. The framework refills it bit by bit: about one more try every 10 seconds for a limit of 6 a minute. - PHP counts a login try against its email before it checks the input. Here, a login that fails validation, such as one without a password, counts only toward the 30 a minute from its IP address. PHP lets an application change these limits by defining its own `restify.login` or `restify.register` limiter. Restify for Rust has no setting for them yet. Each token is a row in `personal_access_tokens` named `login`, in Sanctum's exact format, so a PHP application that shares the database accepts it. To create tokens yourself, see [Creating tokens](sanctum.md#creating-tokens). ### The tokens table Register and login store each token in Sanctum's `personal_access_tokens` table, and the guard reads it from there. A database that came from PHP has this table. A new application must create it. Add this migration, such as `database/migrations/2026_12_03_000001_create_personal_access_tokens_table.rs`. It creates the same table as Laravel Sanctum's own migration, as the example app does: ```rust use laravel::db::AnyTransaction; pub async fn migrate(tx: &mut AnyTransaction<'_>) -> laravel::Result<()> { tx.schema() .create("personal_access_tokens", |table| { table.id(); table.morphs("tokenable"); table.text("name"); table.string("token").length(64).unique(); table.text("abilities").nullable(); table.timestamp("last_used_at").nullable(); table.timestamp("expires_at").nullable().index(); table.timestamps(); }) .await } ``` ## Forgot and reset password Call `password_reset` with the repository of your user model, next to `auth`. This is the example app's `src/lib.rs`: ```rust let restify = Restify::new() .authenticate(Authenticate::via::>()) .auth::() .password_reset::() .profile::(); ``` It adds two routes under `/api`, which a guest can reach: | Request | Body | Answer | | --- | --- | --- | | `POST /api/forgotPassword` | `email`, and `url` if you want your own link | `200`, `{"message": "Reset password link sent to your email."}` | | `POST /api/resetPassword` | `email`, `token`, `password`, `password_confirmation` | `200`, `{"message": "Your password has been successfully reset."}` | **Forgot password** emails the user a link with a new token in it. It answers the same `200` when no user has that email, so nobody can use it to find out who has an account. A second request for the same email within a minute sends no new email. The link is `{frontend}/password/reset?token={token}&email={email}` by default, where `{frontend}` is `FRONTEND_APP_URL`. Change it with `RESTIFY_PASSWORD_RESET_URL`. A request may send its own `url` with `{token}` and `{email}` in it, such as `https://app.example.com/account/reset?token={token}&email={email}`. Its host must be the host of the reset URL or of `FRONTEND_APP_URL` (`APP_URL` when that is not set), or the answer is `422` "The url host is not allowed.", so nobody can send your users a link to another site. **Reset password** checks the token and sets the new password. A token works once, for 60 minutes. A wrong, used or expired token answers `400` with `{"message": "Provided invalid token."}`. After a reset, every Sanctum token of the user is deleted, so the user is logged out everywhere. Set `RESTIFY_REVOKE_TOKENS_ON_RESET=false` to keep them. As in PHP, the new password has no minimum length here: add your own check if you need one. Both answer in at least 200 milliseconds (`RESTIFY_PASSWORD_RESET_TIMEBOX`, in microseconds), whatever happened, so the time an answer takes doesn't tell whether an email has an account. Tokens are kept in Laravel's `password_reset_tokens` table, in PHP's format: the token hashed with bcrypt, one row per email. A PHP application has this table already. A new one needs it, as the example app's migration creates it. Write it like the [tokens table](#the-tokens-table)'s migration: ```rust tx.schema() .create("password_reset_tokens", |table| { table.string("email").primary(); table.string("token"); table.timestamp("created_at").nullable(); }) .await ``` Because the table and the format are PHP's, a link that PHP emailed before the move still resets the password, and PHP accepts a link that Rust emailed. ## Verifying emails Call `email_verification` with the repository of your user model. The example app's tests turn it on this way: ```rust let restify = app::restify().email_verification::(); ``` Then `POST /api/register` also emails the new user a link, and its answer says so in `meta`: ```json "meta": { "email_verification_sent": true, "message": "Registration successful. Please check your email to verify your account." } ``` The link is `POST /api/verify/{id}/{hash}?expires=..&signature=..`. `{hash}` is the SHA-1 of the user's email. The link is signed with `APP_KEY` the way Laravel for PHP signs it, and works for 60 minutes. Keep `APP_KEY` the same as PHP's, and links PHP emailed keep working. Opening the link sets the user's `email_verified_at` and sends the browser to your frontend with the outcome in the query, as PHP does: | Case | Answer | | --- | --- | | The link is good | `302` to `{frontend}/verify/{id}/{emailHash}?success=true&message=Email+verified+successfully.` | | The link was changed, never signed, or is older than 60 minutes | `302`, `success=false&message=Invalid+or+expired+verification+link.` | | The user changed their email since | `302`, `success=false&message=Invalid+hash` | | The user doesn't exist anymore | `404` | Opening a good link again answers the same success. Change the page with `RESTIFY_USER_VERIFY_URL`. Set `user_verify_url` to an empty string in code to answer JSON instead: the user, with `meta.message`, or `403` with the message when the link is bad. The user model needs an `email_verified_at` column. It doesn't need to derive the framework's `MustVerifyEmail`: calling `email_verification` is how you turn it on. Deriving it also makes the framework ask for a verification page on its session guard, which an API doesn't have. Forgot password, reset password and verify each allow 6 requests a minute from one IP address, as in PHP. The seventh answers `429`, as described in [Too many tries](#too-many-tries). ## Changing the emails The emails are the framework's: `ResetPasswordEmail` for a reset link and `VerificationEmail` for a verification link (its `mail.md` and `passwords.md` guides). They are queued and sent with the framework's mailer, so set its `MAIL_*` settings. The framework renders them with MiniJinja: turn on its `minijinja` feature in `Cargo.toml`, as the example app does: ```toml laravel-rust = { version = "0.2", default-features = false, features = ["database-sqlite", "database-postgres", "minijinja"] } ``` Without it the email can't be rendered. Forgot password still answers `200`, as PHP does when its mailer fails, and the error goes to the log. The wording is the framework's, not PHP's. To write your own, put the view in your application, where it replaces the framework's: | Email | Your view | Gets | | --- | --- | --- | | Reset link | `resources/views/vendor/laravel/auth/reset-password.html` | `url`, `token` | | Verification link | `resources/views/vendor/laravel/auth/verify-email.html` | `url` | ## The profile `profile::()` serves the logged-in user at `/api/restify/profile`, behind the provider's middleware: | Request | Does | Asks `authorize` for | | --- | --- | --- | | `GET /api/restify/profile` | Shows the user, as `GET /api/restify/users/{id}` does, with `?related=` | `Show` | | `PUT /api/restify/profile` | Changes the user with the repository's `Update` input | `Update` | | `POST /api/restify/profile` | The same as `PUT` | `Update` | All three answer `{ "data": resource }` with the show fields. Fields the `Update` input doesn't have, such as `is_admin`, are ignored, as in PHP. `PUT` and `POST` are a full update, as `PUT /api/restify/users/{id}` is, and as Restify for PHP's profile update is. So a `required` rule applies to a key the request leaves out, and each field's `can_update` gate is asked. A field that only admins may change with `can_update(is_admin)` stays closed to other users here too. `can_patch` isn't asked, because the profile has no `PATCH`. ## Fields and gates on guest routes Register and login have no guard, because the client has no token yet. On such a route, the framework's `request.user()` fails with "no session guard logs in `User`". A `can_see` gate or a policy that reads the user must check `request.authenticated()` first, as the example app's `is_admin` does: ```rust pub async fn is_admin(request: &Request) -> laravel::Result { // The login and register routes have no guard, and there `request.user()` fails. A guest // isn't an admin. if !request.authenticated().await? { return Ok(false); } let user: Option = request.user().await?; Ok(user.is_some_and(|user| user.is_admin)) } ``` PHP logs the user in before it builds the login answer, so the answer shows the fields that user may see. The framework (`laravel-rust` 0.2) has no public way to log a user into a request without a session guard, so here the login answer shows what a guest may see. A field that only the user may see, such as an admin's own `email`, is missing from it, and the `meta.authorizedTo*` flags are `false`. ## Settings | Variable | `RestifyConfig` field | Default | Does | | --- | --- | --- | --- | | `RESTIFY_TOKEN_TTL` | `token_ttl` | none | Minutes a new token lasts. Sets its `expires_at`, and `meta.expires_in` in seconds | | `SANCTUM_TOKEN_PREFIX` | `SanctumConfig::token_prefix` | empty | Text put before each new token's secret | | `FRONTEND_APP_URL` | `frontend_app_url` | none | Your frontend's address. Starts the default reset and verify pages, and is a host a reset `url` may use. `APP_URL` is used for that host when this isn't set | | `RESTIFY_PASSWORD_RESET_URL` | `password_reset_url` | `{frontend}/password/reset?token={token}&email={email}` | The link in the reset email | | `RESTIFY_USER_VERIFY_URL` | `user_verify_url` | `{frontend}/verify/{id}/{emailHash}` | The page verify sends the browser to. Empty in code: answer JSON | | `RESTIFY_PASSWORD_RESET_TIMEBOX` | `password_reset_timebox` | `200000` | The shortest time, in microseconds, forgot and reset password take to answer | | `RESTIFY_REVOKE_TOKENS_ON_RESET` | `revoke_tokens_on_reset` | `true` | Whether a reset deletes the user's Sanctum tokens | | `SANCTUM_CACHE` | `SanctumConfig::cache` | none | Seconds the guard remembers an accepted token and its user, without asking the database. See [Remembering tokens](sanctum.md#remembering-tokens) for what that changes | These are the names of PHP's `config/restify.php`. Link lifetimes are Laravel's defaults and can't be changed yet: 60 minutes for a reset token, with one email a minute, and 60 minutes for a verification link. --- # Soft Deletes - [Introduction](#introduction) - [Turning soft deletes on](#turning-soft-deletes-on) - [What changes](#what-changes) - [Relationships on other models](#relationships-on-other-models) - [What isn't served](#what-isnt-served) ## Introduction A soft-deleted row stays in its table, with the time it was deleted in a column such as `deleted_at`. In Laravel for PHP, a model with the `SoftDeletes` trait works this way, and Restify for PHP hides those rows from every request. The framework has no soft deletes of its own, so a repository declares the column, and Restify does the rest. ## Turning soft deletes on Give the model a nullable timestamp column, then return it from `soft_deletes`. This is the example app's `PostRepository`: ```rust use laravel::model::Column; use laravel::time::Timestamp; impl Repository for PostRepository { // ... /// Deleted posts stay in the table with a `deleted_at`, and no request reaches them. fn soft_deletes() -> Option>> { Some(Post::deleted_at) } } ``` The migration adds the column with `table.soft_deletes()`. ## What changes With the column declared: - Every request leaves out the rows where the column is set. The list doesn't show them. Show, update, delete, actions and getters answer `404` for them, as for a row that doesn't exist. The MCP tools do the same. - `DELETE /api/restify/posts/{id}` answers `204` as before, but sets `deleted_at` to now instead of removing the row. It is an update, so `updated_at` changes too, as in PHP. The model's `Updated` event fires, not `Deleted`, and the repository's `deleted` hook still runs. - `Repository::query` receives the query with the deleted rows already left out. Without the column, a delete removes the row. ## Relationships on other models `soft_deletes` covers the queries Restify runs for the repository. A relationship declared on another model, such as `User::posts`, is loaded by the framework and doesn't pass through the repository. In PHP, Eloquent left the deleted rows out of those too. Give the relationship a `filter` to do the same, as the example app's `User` model does: ```rust /// The user's posts, without the soft-deleted ones, as Eloquent's `SoftDeletes` leaves them /// out of PHP's `$user->posts`. #[has_many(filter = Post::deleted_at.is_null())] pub posts: HasMany, ``` Without the filter, `?related=posts` would show deleted posts. Your own code outside Restify also sees deleted rows unless it filters them. ## What isn't served Restify for PHP has no route that lists, restores or permanently deletes a soft-deleted row, so neither does this crate. Write your own route if you need one. --- # Bulk Operations - [Introduction](#introduction) - [Allowing bulk requests](#allowing-bulk-requests) - [Creating many models](#creating-many-models) - [Updating many models](#updating-many-models) - [Deleting many models](#deleting-many-models) - [All or nothing](#all-or-nothing) - [Errors](#errors) - [Agents](#agents) ## Introduction A bulk request creates, updates or deletes many models of one repository at once. Restify runs each item through the same code as the single request: the input's validation and the repository's hooks. The request must be allowed the bulk actions, which are separate from the single ones. All the items run in one database transaction, so if one item fails, none of them is saved. The bulk endpoints answer exactly as Restify for PHP's do, so a client written for PHP keeps working. Their answers are therefore simpler than the single endpoints': raw models, an empty object, an empty array. ## Allowing bulk requests Every repository has the bulk endpoints and tools, and refuses them until its `authorize` allows the bulk actions. They are separate from the single ones, so a repository may let a user change one post and not fifty: | Action | Asked | `model` is | | --- | --- | --- | | `Action::StoreBulk` | Once for the request | `None` | | `Action::UpdateBulk` | For each item, after every model is found and before any is changed | The model, before the change | | `Action::DeleteBulk` | For each item, after every model is found and before any is deleted | The model | The example app lets only an admin write posts in bulk: ```rust async fn authorize(action: Action, request: &Request, post: Option<&Post>) -> laravel::Result<()> { match (action, post) { (Action::AllowRestify | Action::Index | Action::Store, _) => Ok(()), (Action::Show, Some(post)) => request.authorize(PostPolicy::show, post).await, (Action::Update, Some(post)) => request.authorize(PostPolicy::update, post).await, (Action::Delete, Some(post)) => request.authorize(PostPolicy::delete, post).await, (Action::StoreBulk | Action::UpdateBulk | Action::DeleteBulk, _) => { request.authorize(PostPolicy::bulk, ()).await } _ => Err(laravel::abort(403)), } } ``` A request may hold at most `MAX_BULK` items, `100` by default. Restify for PHP has no limit; this one is a safety limit, so that one request can't hold a database transaction open for long. To change it, set it on the repository: ```rust const MAX_BULK: usize = 20; ``` ## Creating many models Send a JSON array of `Store` inputs to `POST /api/restify/posts/bulk`: ```json [ { "title": "First", "votes": 1 }, { "title": "Second", "body": "Text" } ] ``` It answers `200` with every new model, in the order sent. As in Restify for PHP, each model is its own JSON, not a resource: no `type` and no `attributes`, the key as a number, and no field rules applied, so a hidden column such as `body` shows: ```json { "data": [ { "id": 1, "title": "First", "votes": 1, "user_id": 1, "created_at": "..", "updated_at": ".." }, { "id": 2, "title": "Second", "body": "Text", "user_id": 1, "created_at": "..", "updated_at": ".." } ] } ``` A column the item could have set but left out, such as `body` in the first item, isn't shown. Read the posts again with `GET` to see them as resources. Restify calls `authorize` once with `Action::StoreBulk` and validates every item. Then, for each item, it runs `creating`, saves it, and runs `stored`. ## Updating many models Send a JSON array to `POST /api/restify/posts/bulk/update`. Each item is the model's `id` and the `Update` fields to change: ```json [ { "id": 1, "title": "Laravel for Rust", "votes": 11 }, { "id": "2", "title": "Renamed" } ] ``` It answers `200` with an empty object, `{}`, as Restify for PHP does. An `id` may be a number or a string. A bulk update is a full update, like `PUT`: a field with a `required` rule, such as the post's `title`, must be in every item. Other fields an item leaves out keep their values. Restify validates every item, finds every model through `Repository::query`, and calls `authorize` with `Action::UpdateBulk` for each. Then, for each item, it runs `updating`, saves it, and runs `updated`. ## Deleting many models Send a JSON array of ids to `DELETE /api/restify/posts/bulk/delete`: ```json [1, 2, 3] ``` It answers `200` with an empty array, `[]`, as Restify for PHP does. An id sent twice deletes its model once. Restify finds every model through `Repository::query` and calls `authorize` with `Action::DeleteBulk` for each. Then it deletes each one and runs `deleted`. ## All or nothing Restify checks the whole request before it writes anything: every item's input, every model, and every permission. Then it writes the items one after another, in the order sent, inside one database transaction (the framework's `db::transaction`). If a hook fails part way, the transaction rolls back every item before it. So a client never has to work out which items were saved. - A `422` lists the errors of every item at once, so a client can fix them all and send the request again. - Events and queued jobs the framework dispatches wait for the transaction to commit, so a rolled-back request sends nothing. See the framework's `database.md` guide, "Transactions". ## Errors A field error's key starts with the item's position in the array, starting at `0`. Here the second item has no title: ```json { "message": "A post needs a title.", "errors": { "1.title": ["A post needs a title."] } } ``` The message is the field's own, as on the single endpoints. A message the rule writes itself names the item, such as "The 1.title field is required.". Restify for PHP leaves out a field's own messages in bulk, and answers "The 1.title field is required." here. That is a bug in PHP. The status and the error keys are the same. A refusal answers `403` and a missing model `404`, with the same message as the single endpoints. | Status | When | | --- | --- | | `401` | The middleware found no user | | `403` | `authorize`, a policy, or the input's own check refused an item | | `404` | No model has an item's id, or `query` leaves it out | | `422` | An item is invalid, or an update item has no `id`; or the body isn't an array, is empty, or holds more than `MAX_BULK` items | A key the input doesn't declare, such as `user_id`, is ignored, as on the single endpoints and in Restify for PHP. A field's write gates apply to each item as they do to a single write: `can_store` in a bulk create, `can_update` in a bulk update, and `readonly_when` in both. A key a gate refuses is dropped from that item. See [Fields only some users may write](writing.md#fields-only-some-users-may-write). The errors about the array itself use the key `items`: `"items": ["Send at most 100 items at once. This request sent 150; split it into smaller requests."]`. ## Agents There are no bulk MCP tools, as in Restify for PHP. An agent creates, updates or deletes one record per call. See [MCP](mcp.md). --- # MCP - [Introduction](#introduction) - [Letting agents use a repository](#letting-agents-use-a-repository) - [Choosing a mode](#choosing-a-mode) - [Read-only mode](#read-only-mode) - [The tools in direct mode](#the-tools-in-direct-mode) - [The tools in wrapper mode](#the-tools-in-wrapper-mode) - [Searching every repository](#searching-every-repository) - [What a tool returns](#what-a-tool-returns) - [When a call fails](#when-a-call-fails) - [Behaviour kept from Restify for PHP](#behaviour-kept-from-restify-for-php) - [Connecting an agent](#connecting-an-agent) - [Calling the MCP server from a browser](#calling-the-mcp-server-from-a-browser) - [Writing for agents](#writing-for-agents) - [The protocol](#the-protocol) ## Introduction Restify serves a [Model Context Protocol](https://modelcontextprotocol.io) server at `POST /mcp/restify`. AI agents use it to list, read, create, change and delete your records, and to run your [actions and getters](actions.md). It answers as Restify for PHP's MCP server does: the same tool names, arguments, hints and results. An MCP client set up for a PHP Restify application keeps working against a Rust one. A tool runs the same code as the matching endpoint. `authorize`, `query`, the validation rules and the fields apply to agents exactly as they do to other clients. Middleware apply too, but differently. The server's route is behind the provider's middleware, so `Restify::authenticate` and `Restify::middleware` run on every MCP request. A repository's own `middleware()` runs before each of its tools, as a check: it may refuse the tool or change the request, but code it runs after `next.run(request)` doesn't run there. The `global-search` tool runs the middleware of each repository it searches, and one refusal refuses the whole search. See [Where the middleware run](repositories.md#where-the-middleware-run). Nothing is served until you allow it. A repository opts in with `const MCP`. The server is the crate's `mcp` feature, on by default. An application that serves no agents may turn it off to leave out its code and the `rmcp` crate: see [Choosing features](installation.md#choosing-features). ## Letting agents use a repository Set `const MCP` on the repository. `McpTools::INDEX` allows the list only, which is what PHP's `HasMcpTools` trait allows by default. `McpTools::ALL` allows everything: ```rust impl Repository for PostRepository { // ... /// Agents may do everything with posts that the endpoints allow. const MCP: Option = Some(McpTools::ALL); } ``` To allow some operations, turn them on with `McpTools::INDEX` and the method named after each operation: ```rust impl Repository for CommentRepository { // ... /// Agents may list comments and read one. const MCP: Option = Some(McpTools::INDEX.show(true)); } ``` | Field | Allows | PHP method | | --- | --- | --- | | `index` | The list | `mcpAllowsIndex` | | `show` | One record | `mcpAllowsShow` | | `store` | Creating | `mcpAllowsStore` | | `update` | Changing | `mcpAllowsUpdate` | | `delete` | Deleting | `mcpAllowsDelete` | | `actions` | Each action | `mcpAllowsActions` | | `getters` | Each getter | `mcpAllowsGetters` | A repository without `const MCP` has no tools. Its relationships are also left out of what the tools of other repositories return. The repository you pass to `Restify::profile` also gets a profile tool, when it sets `const MCP`. To give agents fewer fields than other clients, use `hide_from_mcp` on a field, or return other fields for `View::McpIndex` and `View::McpShow` from `fields_for`. See [Fields](fields.md). ## Choosing a mode The server lists its tools in one of two ways, as PHP's `mcp.mode` does. Set `RESTIFY_MCP_MODE`: | Mode | `tools/list` shows | Best for | | --- | --- | --- | | `wrapper`, the default | `global-search`, and four tools that find and run every operation | Many repositories: the agent's tool list stays short | | `direct` | `global-search`, and one tool per operation of each repository | Few repositories: the agent sees every operation at once | Both modes serve the same operations to the same users, and both run the same code. ## Read-only mode Set `RESTIFY_MCP_READ_ONLY=true` to let agents read but never write, as PHP's `mcp.read_only` does. The tools that create, update or delete, and every action, are no longer served: - In `direct` mode, they aren't listed, and calling one answers as an unknown tool. - In `wrapper` mode, `discover-repositories` and `get-repository-operations` don't show them. `get-operation-details` answers `OPERATION_DETAILS_ERROR`, and `execute-operation` answers `AUTHORIZATION_ERROR`. Getters still run: they only read. ## The tools in direct mode For a repository named `posts`, after [`global-search`](#searching-every-repository): | Tool | Does | Arguments | Hint | | --- | --- | --- | --- | | `posts-index-tool` | Lists a page | `page`, `perPage`, `include`, `search`, `sort`, and each filter column | `readOnlyHint` | | `posts-show-tool` | Returns one | `id`, `include` | `readOnlyHint` | | `posts-store-tool` | Creates one | The fields of `Store`, `include` | none | | `posts-update-tool` | Changes one | `id`, the fields of `Update`, `include` | `idempotentHint` | | `posts-delete-tool` | Deletes one | `id` | `destructiveHint`, `idempotentHint` | | `posts-{key}-action-tool` | Runs an [action](actions.md) | `resources` for an action on the list, `id` for one on a single record, and the fields of its input | `openWorldHint`, and `destructiveHint` set to the action's `DESTRUCTIVE` | | `posts-{key}-getter-tool` | Runs a [getter](actions.md) | `id` for a getter on a single record, and the fields of its input | `readOnlyHint` | | `users-profile-tool` | Returns the logged-in user's profile | `include` | `readOnlyHint` | An action's tool says whether it destroys data: `destructiveHint` is `true` when the action sets `const DESTRUCTIVE: bool = true`, and `false` otherwise. Restify for PHP leaves the hint out, and the protocol reads a missing `destructiveHint` as `true`, so to an agent every PHP action looks destructive. This is a deliberate difference. The wrapper tools show the same hints under `annotations`. Each tool's title is the repository's name and the operation, such as `Posts Index`. An action or getter's title is its name. The profile tool's title is `Profile Tool`. The list arguments mean what the query string parameters mean in [Filtering](filtering.md). `include` names relationships, as `?related=` does in [Relationships](relationships.md). A repository that declares no sortable field may still be sorted by its key, such as `sort=posts.id`. The schemas of the store and update tools come from `#[derive(Schema)]` on the input structs, as [Writing](writing.md) describes. An action or getter whose `can_see` refuses the user isn't listed for that user, and calling it answers as an unknown tool. To see the tools an application serves, run `laravel restify:list --json`. ## The tools in wrapper mode After [`global-search`](#searching-every-repository): | Tool | Does | Arguments | | --- | --- | --- | | `discover-repositories` | Lists the repositories the user may use, with their operations | `search`, optional | | `get-repository-operations` | Lists one repository's operations, actions and getters | `repository` | | `get-operation-details` | Returns one operation's arguments as a JSON Schema, with examples | `repository`, `operation_type`, and `operation_name` for an action or getter | | `execute-operation` | Runs one operation | `repository`, `operation_type`, `operation_name` for an action or getter, and `parameters` | `operation_type` is one of `index`, `show`, `store`, `update`, `delete`, `profile`, `action` and `getter`. `operation_name` is the action or getter's key, such as `publish-posts-action`. `parameters` holds the arguments that the matching direct-mode tool takes. For example, an agent lists posts with: ```json { "repository": "posts", "operation_type": "index", "parameters": { "perPage": 5, "sort": "-votes" } } ``` ## Searching every repository Both modes list `global-search` first, as PHP does. It runs the same search as `GET /api/restify/search`, described in [Global search](filtering.md#global-search), with the agent's `search` argument: ```json { "search": "rust" } ``` It answers with the results, how many there are, and the repositories it searched. Shortened, from the example app: ```json { "results": [ { "repositoryName": "posts", "repositoryTitle": "Posts", "title": "Rust ownership explained", "subTitle": "20 votes", "repositoryId": 4, "link": "/api/restify/posts/4" } ], "total": 1, "searched_repositories": [{ "name": "posts", "title": "Posts" }] } ``` The tool doesn't need `const MCP`. It searches exactly the repositories that `Restify::global_search::()` added, which also answer `/search`. So the tool is always listed, but it finds nothing until a repository is added. This differs from PHP, where every repository is searched unless it opts out. The `limit` argument is accepted and ignored, as in PHP: each repository returns at most its `GlobalSearch::RESULTS`. The tool reads, so read-only mode keeps it. ## What a tool returns A successful call returns JSON twice: as `structuredContent`, and as the text of its one content block. `global-search` is the one exception: as in PHP, it returns the JSON only as text. | Operation | Returns | | --- | --- | | List | The same document as the endpoint, with `data`, `meta` and `links`. The page URLs in `links` and `meta.path` are the MCP server's, such as `https://example.com/mcp/restify?page=2`, as in PHP: they lead nowhere, so page with the `page` argument | | Show | The resource itself: `id`, `type`, `attributes`, `relationships` and `meta`, without the `data` key | | Create, update | `{ "data": { ... } }`, with only the attributes the input may write, and the relationships `include` names | | Delete | `{ "id": "1", "deleted": true }`, with the `id` as the agent sent it | | Action | `{ "success": true, "action": "publish-posts-action", "result": { ... } }`, where `result` is what `handle` answered | | Getter | `{ "success": true, "getter": "stats", "result": { ... } }` | | Profile | The users list, as the list tool returns it | An action whose `can_run` refuses the user is not a failed call. It returns `{ "error": "...", "action": "publish-posts-action" }` with `isError: false`. The wrapper tools return what the matching direct-mode tool returns. `discover-repositories`, `get-repository-operations` and `get-operation-details` return JSON that lists what they found and a `next_steps` list for the agent. ## When a call fails A failed call is a result with `isError: true` and one text block, so the agent can read the reason and correct itself. In direct mode, the text is what Laravel's MCP server says for the error: | Error | Text | | --- | --- | | Invalid input | Every validation message, joined with spaces, such as `A post needs a title. The votes field must be at least 0.` | | Refused by `authorize` or a policy | `This action is unauthorized.` | | No logged-in user | `Unauthenticated.` | | Anything else, a missing record included | `An internal server error occurred.` The details are in the application's log | In wrapper mode, the text is a JSON object with an `error` message and a `code`. A validation error also has `errors`, the messages of each field: ```json { "error": "Validation failed", "code": "VALIDATION_ERROR", "errors": { "title": ["A post needs a title."] } } ``` | Code | Means | | --- | --- | | `MISSING_PARAMETER` | `repository`, `operation_type` or `operation_name` is missing | | `INVALID_REPOSITORY` | The repository doesn't exist, doesn't set `const MCP`, or the user may use none of its operations | | `INVALID_OPERATION` | The repository doesn't serve that operation to this user, or `operation_type` is unknown. An unknown type, action or getter is answered with the names that are valid | | `INVALID_PARAMETERS` | `parameters` isn't an object | | `VALIDATION_ERROR` | The input is invalid | | `AUTHORIZATION_ERROR` | The user may not run the operation, or read-only mode refuses it | | `NOT_FOUND` | The record doesn't exist | | `EXECUTION_ERROR` | Anything else. The details are in the application's log | | `OPERATION_DETAILS_ERROR` | `get-operation-details` failed, or read-only mode refuses the operation | For example, `operation_type: "export"` answers `Unknown operation_type "export". Valid operation types: index, show, ...`, and an action the user may not run answers `Unknown action "archive-posts-action" on "posts". Valid action names: publish-posts-action, export-posts-action.`, in the same words as Restify for PHP. ## Behaviour kept from Restify for PHP Agents written for PHP Restify rely on these, so the crate keeps them: - **An action on the list reads its records from `repositories`.** Its schema asks for `resources`, but the tool ignores that argument. Without `repositories`, the action runs on no record. `repositories` may be a list of ids or a JSON text of one, such as `"[1, 2]"`. - **The profile tool returns the users list**, not only the logged-in user. It runs the list with the user's id as an argument that the list doesn't read. It passes the agent's other arguments on to the list too. It exists whenever the profile's repository sets `const MCP`, even when `McpTools.index` is `false`. It asks `Action::Index` and shows what the list would show this user. So it reveals nothing the users list doesn't, but an agent may see every user. Safe setup: narrow the users in `UserRepository::query` for `Action::Index`, such as to the user alone for users who aren't admins. Or don't give the user repository `const MCP`. - **`global-search` searches every repository added with `Restify::global_search`**, including those without `const MCP`, and its description names their searchable columns. Safe setup: add a repository to the global search only if agents may read its rows. Rows are still filtered by `AllowRestify`, `query` and `Show` for each request. - **In `direct` mode, `tools/list` lists every repository's tools**, including those whose `Action::AllowRestify` refuses the user. A listed tool only shows names and input schemas. Calling it still asks `AllowRestify` and refuses. Safe setup: keep a repository that some users may never use out of the MCP server (no `const MCP`), or use `wrapper` mode, whose `discover-repositories` leaves those repositories out. - **The update tool changes a record as `PUT` does.** Its schema marks the fields that a full update needs as required, and leaving one out is a validation error. - **A missing record is an internal error in direct mode**, not a "not found" error. - **The input ignores arguments it doesn't declare**, as the endpoints do. ## Connecting an agent The server speaks Streamable HTTP. Point an MCP client at the application's URL and send the API token as a bearer token. For Claude Code: ```shell claude mcp add --transport http shop https://example.com/mcp/restify --header "Authorization: Bearer " ``` Change the path with `Restify::new().mcp("/mcp/shop")`, and turn the server off with `.without_mcp()`. ## Calling the MCP server from a browser The server refuses a request whose `Origin` header names another site, with `403`, as the MCP specification requires of a Streamable HTTP server. A browser sends that header, so this protects a server on a developer's machine from a web page in their browser, which could otherwise reach it through DNS rebinding. Agents and other clients that aren't browsers send no `Origin`, and pass. The server's own origin passes: the scheme, host and port of the request, such as `https://example.com`. A page anywhere else, such as a frontend on `http://localhost:5173` calling an API on `http://localhost:8000`, gets: ```json { "jsonrpc": "2.0", "error": { "code": -32600, "message": "The request's origin isn't allowed." } } ``` To let your own frontend call the server, list its origin in the framework's CORS settings, `src/config/cors.rs`, and add the server's path to `paths`. The browser needs that anyway, for the preflight request it sends before a `POST` with `Content-Type: application/json`. The server accepts every origin that `origins` lists, with `*` as a wildcard, and every origin that `origin_patterns` matches, when a pattern of `paths` matches its path. The example app's `src/config/cors.rs` is the starter's, with `mcp/*` and two origins: ```rust use laravel::config; use laravel::config::cors::{Allowed, Cors}; use laravel::time::ToSpan; #[config::section] fn cors() -> Cors { Cors { paths: vec!["api/*".to_owned(), "mcp/*".to_owned()], methods: Allowed::Any, origins: Allowed::only(["http://localhost:5173", "https://*.example.org"]), origin_patterns: Vec::new(), headers: Allowed::Any, exposed_headers: Vec::new(), max_age: Some(0.seconds().into()), credentials: false, } } ``` `Allowed::Any`, the framework's default, lists no origin, so it doesn't open the server: list each origin. An origin listed only for `api/*` doesn't open it either. Nothing else changes for those requests: the token, the middleware and `authorize` apply as for any client. The framework's guide on [CORS](https://github.com/laravel/rust-framework/blob/0.x/docs/routing.md#cors) describes the section. ## Writing for agents An agent knows only what the tools tell it. Three habits make a repository easy for an agent to use correctly: - **Document every input field** with a doc comment. It becomes the field's description. - **Put rules in `#[validate(..)]`**, not in a hook. A rule the schema shows is one the agent follows the first time, and a validation error names the field to fix. - **Mark the fields an agent will want** `searchable`, `matchable` and `sortable`. An agent can't filter by a column the repository doesn't mark. ## The protocol The server is built on [`rmcp`](https://crates.io/crates/rmcp), the official Rust SDK for MCP. It speaks Streamable HTTP and follows what that SDK implements. - Its name in `initialize` is `Laravel Restify`, with PHP's instructions. Its version is the crate's. - It answers `server/discover`, `initialize`, `ping`, `tools/list` and `tools/call`. Its `initialize` announces tools, resources and prompts, each with `listChanged: false`, as PHP's server does, but it has no resources or prompts: `resources/list` and `prompts/list` answer empty lists. PHP's server has no prompts either, and lists one resource, `file://instructions/application-info.md`, a text about the application and its versions, which this server doesn't serve. - It speaks every protocol version from `2024-11-05` to the current `2026-07-28`. A `2026-07-28` client names the version in each request. An older client agrees on it with `initialize`, which answers with the client's version when the server knows it, and `2025-11-25` otherwise. - Each request is independent: there are no sessions, and each answer is one JSON object. The server sends no requests of its own. - A client must accept both `application/json` and `text/event-stream` (`406` otherwise) and send `Content-Type: application/json` (`415` otherwise). - A `2026-07-28` request must repeat its version, method and tool name in the `MCP-Protocol-Version`, `Mcp-Method` and `Mcp-Name` headers. A header that doesn't match the body is refused with `400` and error `-32020`. - A request whose `Origin` header names another site is refused with `403`, unless the framework's CORS settings list that origin for the server's path. See [Calling the MCP server from a browser](#calling-the-mcp-server-from-a-browser). - An unknown tool, or one the user may not use, answers JSON-RPC error `-32602` with the message `Tool [name] not found.`, with HTTP status `200`. PHP sends the same error with status `400`. An unknown method answers `-32601`, with HTTP status `404` for a `2026-07-28` request. Laravel is adding MCP servers to the framework itself. When that ships, Restify will register its tools with it and this server will go away. The tools, their names and their results will stay the same. --- # OpenAPI - [Introduction](#introduction) - [Printing the document](#printing-the-document) - [Serving the document](#serving-the-document) - [Describing a model's attributes](#describing-a-models-attributes) - [What the document contains](#what-the-document-contains) - [What it leaves out](#what-it-leaves-out) ## Introduction Restify can describe its HTTP endpoints as an [OpenAPI 3.1](https://spec.openapis.org/oas/v3.1.0) document. API clients, SDK generators and AI agents read it to learn every endpoint, parameter, request body and response. The document is built from the same facts as the MCP tools and `restify:list`: the repositories, their fields, and the `#[derive(Schema)]` of their input structs. There is no second description to keep in sync. The document is the crate's `openapi` feature, on by default. Without it, `.openapi(..)` and the `restify:openapi` command don't exist: see [Choosing features](installation.md#choosing-features). ## Printing the document ```shell laravel restify:openapi laravel restify:openapi --output openapi.json ``` The first command prints the document as JSON. The second writes it to a file instead. Both work whether or not the application serves the document. ## Serving the document The document isn't served by default. To serve it, name a path inside the prefix: ```rust Restify::new() .authenticate(Authenticate::via::>()) .openapi("/openapi.json") .openapi_version(env!("CARGO_PKG_VERSION")) .repository::() ``` The application then answers `GET /api/restify/openapi.json`. The provider's middleware runs first, as it does for every other endpoint, so with the example above a client needs an API token to read it. The document's settings come from the application: | Field | Value | | --- | --- | | `info.title` | `APP_NAME` | | `info.version` | `.openapi_version(..)`. Default `1.0.0` | | `servers` | `APP_URL` | ## Describing a model's attributes There is nothing to write. The document lists a resource's `attributes` from the repository's [fields](fields.md): each field's name, and the JSON Schema of its column's type. | In `Repository::fields` | In `attributes` | | --- | --- | | `Field::new(Post::title)` | A property with the column's type | | A column of `Option` | The type or `null` | | `Field::computed("excerpt", ..)`, `Field::computed_with(..)` | A property with the type the function returns | | `.label("headline")` | The property's name | | `.description("..")` | `description` | | `.as_integer()`, `.decimals(2)` | The type the field then writes: an integer, a string | | `Field::query_only(..)` | Left out | | A column no field lists | Left out | A field of a type the document doesn't know needs `restify::Property`. See [Fields](fields.md#how-each-type-is-written). `attributes` requires no field. A list shows fewer fields than one record, and a field with `can_see` is left out for the requests that don't pass it, so the document lists every field that any HTTP view shows and promises none. A client may rely on a field's type whenever the field is there. ## What the document contains For a repository named `posts`: | Operation | `operationId` | Request | Success | | --- | --- | --- | --- | | `GET /api/restify/posts` | `posts.index` | The list parameters | `200`, `posts.page` | | `POST /api/restify/posts` | `posts.store` | `posts.store` | `201`, `posts.document`, with a `Location` header | | `GET /api/restify/posts/{id}` | `posts.show` | | `200`, `posts.document` | | `PUT /api/restify/posts/{id}` | `posts.update` | `posts.update` | `200`, `posts.document` | | `PATCH /api/restify/posts/{id}` | `posts.patch` | `posts.update` | `200`, `posts.document` | | `DELETE /api/restify/posts/{id}` | `posts.delete` | | `204` | Every repository has the bulk endpoints. Its actions and getters appear when it lists them: | When the repository | Operation | `operationId` | Request | Success | | --- | --- | --- | --- | --- | | Lists any action | `GET /api/restify/posts/actions` and `/{id}/actions` | `posts.actions.index`, `posts.actions.show` | | `200`, the listing | | Lists an action on the list, or a standalone one | `POST /api/restify/posts/actions` | `posts.actions.perform` | `?action=` and one of the actions' bodies | `200`, `Output` | | Lists an action on one model, or a standalone one | `POST /api/restify/posts/{id}/actions` | `posts.actions.perform-show` | `?action=` and one of the actions' bodies | `200`, `Output` | | Lists any getter | `GET /api/restify/posts/getters` and `/{id}/getters` | `posts.getters.index`, `posts.getters.show` | | `200`, the listing | | Lists the getter `stats` on the list | `GET /api/restify/posts/getters/stats` | `posts.getter.stats` | | `200`, `Output` | | Lists the getter `word-count` on one model | `GET /api/restify/posts/{id}/getters/word-count` | `posts.getter.word-count` | | `200`, `Output` | | Always | `POST /api/restify/posts/bulk` | `posts.bulk-store` | An array of `posts.store` | `200`, `{ "data": [..] }` of models | | Always | `POST /api/restify/posts/bulk/update` | `posts.bulk-update` | An array of `posts.update`, each with an `id` | `200`, `{}` | | Always | `DELETE /api/restify/posts/bulk/delete` | `posts.bulk-delete` | An array of ids | `200`, `[]` | The document also has these, each with its own `operationId`: - `GET /api/restify/posts/filters` and `POST /api/restify/posts/apply-restify-advanced-filters`, for every repository. See [Advanced filters](filtering.md#advanced-filters). - `DELETE /api/restify/posts/{id}/field/{field}`, when the repository's update input takes a file. See [Files and images](files.md). - The nested routes of each relationship shown with `through` or `many`, such as `GET /api/restify/posts/{id}/comments/{relatedId}`, and the attach, detach and sync routes of each `Related::many`. See [Relationships](relationships.md#nested-routes). - `GET /api/restify/search`, once, when a repository was added with `global_search`. See [Global search](filtering.md#global-search). The account endpoints appear when the provider serves them, with the tag `accounts`. Their bodies come from the input structs their handlers check, so the document shows the same fields and rules, and `password_confirmation` where the `confirmed` rule asks for it. See [Authentication](authentication.md). | When the provider calls | Operation | `operationId` | Success | | --- | --- | --- | --- | | `Restify::auth` | `POST /api/register`, `POST /api/login` | `register`, `login` | `200`, the user with `meta.token` | | `Restify::auth` | `POST /api/logout` | `logout` | `200`, `{ "message" }` | | `Restify::password_reset` | `POST /api/forgotPassword`, `POST /api/resetPassword` | `forgotPassword`, `resetPassword` | `200`, `{ "message" }` | | `Restify::email_verification` | `POST /api/verify/{id}/{hash}` | `verify` | `200`, the user with `meta.message`, or a `302` to the frontend | | `Restify::profile` | `GET` and `PUT /api/restify/profile` | `profile.show`, `profile.update` | `200`, `users.document` | The answers refer to the user repository's schemas, such as `users.attributes`, when the provider serves that repository too. Register is the exception: it answers the new user as it was built, before the database filled in its defaults, so such a column shows `null`, as in Restify for PHP. Its `attributes` are described as any object. Each throttled route also lists its `429`. Each operation has the tag `posts` and lists the errors it can answer, as in [Reference](reference.md#errors): - Every operation can answer `401` and `403`. - An operation on one record, with `{id}` in its path, can answer `404`. So can a bulk update or delete, when an item's id isn't found. - An operation that reads input or list parameters can answer `422`. A getter takes no input, so it never does. `?action=` lists the keys of the actions that run there. The request body is `anyOf` the actions' inputs, from their `#[derive(Schema)]`, with a required `repositories` for an action on the list. The body is never marked required, because an action whose input has no required field accepts an empty body. The operation's `description` lists each action's key with its `DESCRIPTION`. The `/action` paths, PHP's other name for `/actions`, aren't listed. A bulk body is an array of 1 to `MAX_BULK` items (`minItems` and `maxItems`). Its `422` response says how the errors name an item: by its position, from `0`, such as `1.title`, and `items` for errors about the array itself. See [Bulk operations](bulk.md#errors). The list parameters are: `search` when the repository has searchable fields, `sort` with the columns and scopes it may sort by, `page`, `perPage`, `related` when the repository lists relationships, and each filter column and scope with and without a leading `-`. Show takes `related` too. The schemas live in `components.schemas`: | Schema | Holds | | --- | --- | | `posts.store`, `posts.update` | The `#[derive(Schema)]` of `Store` and `Update` | | `posts.attributes` | The repository's fields, none required | | `posts.resource` | `id` (a string), `type` (the repository's `resource_type`), `attributes`, and `relationships` when the repository lists relationships | | `posts.document` | `{ "data": resource }` | | `posts.page` | `meta`, `links` and `data`, as in [Reference](reference.md#a-page) | | `posts.list` | `{ "data": [resource, ..] }`, what a bulk create or update answers | | `Relationship` | One `RelatedResource`, a list of them, or `null` | | `RelatedResource` | A related model: `id`, `type` (its table) and `attributes` | | `Output` | What an action or getter answered. Restify can't see what `handle` returns, so it may be any JSON | | `Error`, `ValidationError` | `{ "message" }` and `{ "message", "errors" }` | `relationships` lists each name from `Repository::related`, and none is required, because a response has only the ones the request named. Restify doesn't know whether a relationship holds one record or many, so each is a `Relationship`: one record, a list, or `null`. See [Relationships](relationships.md#what-a-response-contains). The example app's tests check the document against the official OpenAPI 3.1 schema, and check real responses against the document's own schemas. ## What it leaves out - **The MCP server.** It speaks JSON-RPC, not REST. MCP clients read its tools with `tools/list`. See [MCP](mcp.md). - **Authentication.** Restify can't see what a middleware checks, so the document has no `securitySchemes`. - **Filter value types.** A filter is described as text, the way the query string carries it. - **What an action or getter returns.** `handle` returns a `Reply` of any JSON, which has no schema. - **Numeric ids in bulk bodies.** A bulk update or delete also accepts an id as a number, but the document lists ids as strings. - **Extra fields in a body.** The input schemas refuse properties they don't declare. An HTTP endpoint and an MCP tool ignore such fields instead. --- # Reference - [Endpoints](#endpoints) - [List parameters](#list-parameters) - [A resource](#a-resource) - [A page](#a-page) - [Errors](#errors) - [Commands](#commands) Paths below are for a repository named `posts` with the default prefix. ## Endpoints | Request | Action | Success | Body | | --- | --- | --- | --- | | `GET /api/restify/posts` | `Index` | `200` | [A page](#a-page) | | `GET /api/restify/posts/{id}` | `Show` | `200` | `{ "data": resource }` | | `POST /api/restify/posts` | `Store` | `201`, with a `Location` header | `{ "data": resource }` | | `PUT /api/restify/posts/{id}` | `Update` | `200` | `{ "data": resource }` | | `POST /api/restify/posts/{id}` | `Update` | `200` | `{ "data": resource }`, as `PUT` | | `PATCH /api/restify/posts/{id}` | `Update` | `200` | `{ "data": resource }` | | `DELETE /api/restify/posts/{id}` | `Delete` | `204` | Empty | | `DELETE /api/restify/documents/{id}/field/{field}` | `Update` | `204`, or `404` when `{field}` isn't a deletable file field | Empty. Deletes one file field's file. See [Files and images](files.md#replacing-and-deleting-files) | | `GET /api/restify/posts/actions` and `/{id}/actions` | The action's `can_see` | `200` | `{ "data": [action, ..] }` | | `POST /api/restify/posts/actions?action={key}` (or `/action`) | The action's `can_run` | `200` | What `handle` returned | | `POST /api/restify/posts/{id}/actions?action={key}` (or `/{id}/action`) | The action's `can_run` | `200` | What `handle` returned | | `GET /api/restify/posts/getters` and `/{id}/getters` | The getter's `can_see` | `200` | `{ "data": [getter, ..] }` | | `GET /api/restify/posts/getters/{key}` | The getter's `can_run` | `200` | What `handle` returned | | `GET /api/restify/posts/{id}/getters/{key}` | The getter's `can_run` | `200` | What `handle` returned | | `GET /api/restify/posts/filters` | `AllowRestify` | `200` | `{ "data": [filter, ..] }`. See [Listing the filters](filtering.md#listing-the-filters) | | `POST /api/restify/posts/apply-restify-advanced-filters` | `Index` | `200` | [A page](#a-page), filtered by the body's `filters`. See [Advanced filters](filtering.md#advanced-filters) | | `GET /api/restify/search?search=..` | `AllowRestify` and `Show`, in each repository added with `global_search` | `200` | `{ "data": [result, ..] }`. See [Global search](filtering.md#global-search) | | `POST /api/restify/posts/bulk` | `StoreBulk`, once | `200` | `{ "data": [model, ..] }`, each model's own JSON | | `POST /api/restify/posts/bulk/update` | `UpdateBulk`, per item | `200` | `{}` | | `DELETE /api/restify/posts/bulk/delete` | `DeleteBulk`, per item | `200` | `[]` | | `GET /api/restify/posts/{id}/comments` and `/{id}/comments/{commentId}` | `Show` on the post, then the comments' own action | As `GET /comments` and `GET /comments/{id}` | Only the post's comments. See [Relationships](relationships.md#nested-routes) | | `POST`, `PUT`, `PATCH`, `DELETE` under `/api/restify/posts/{id}/comments` | `Show` and `Update` on the post, then the comments' own action | As the comments' own routes | The post's key is set on a new comment | | `POST /api/restify/teams/{id}/attach/users` | `Attach("users")`, per user | `201` | `{ "data": [join row, ..] }` | | `POST /api/restify/teams/{id}/detach/users` | `Detach("users")`, per user | `204` | Empty | | `POST /api/restify/teams/{id}/sync/users` | `Sync("users")`, once | `200` | `[]` | | `POST /mcp/restify` | | `200`, or `202` for a notification | A JSON-RPC message | | `GET /api/restify/profile` | `Show`, on the logged-in user | `200` | `{ "data": resource }` | | `PUT` or `POST /api/restify/profile` | `Update`, on the logged-in user | `200` | `{ "data": resource }` | | `POST /api/register` | None | `200` | resource, with `meta.token` | | `POST /api/login` | None | `200` | resource, with `meta.token` | | `POST /api/logout` | None | `200` | `{ "message": "Successfully logged out." }` | | `POST /api/forgotPassword` | None | `200` | `{ "message": "Reset password link sent to your email." }` | | `POST /api/resetPassword` | None | `200` | `{ "message": "Your password has been successfully reset." }` | | `POST /api/verify/{id}/{hash}` | None; the link's signature | `302` | Empty; `location` is your frontend's page | These routes are only there when the application turns them on: `profile` adds the profile, `auth` adds register, login and logout, `password_reset` adds forgot and reset password, and `email_verification` adds verify. See [Authentication](authentication.md). Every request is first asked for `Action::AllowRestify`, without a model. See [Authorization](authorization.md). Create and update take a JSON object of the input struct's fields, at the top level: `{ "title": "Hello" }`. So does an action, and an action on the list also takes `repositories`. See [Actions and getters](actions.md). The three bulk endpoints take a JSON array: of `Store` inputs, of `{ "id": .., ..fields }`, or of ids. See [Bulk operations](bulk.md). ## List parameters | Parameter | Example | Does | | --- | --- | --- | | `search` | `?search=rust` | Keeps rows where a search column contains the text | | A filter column or scope | `?votes=10`, `?filter[votes]=10`, `?body=null` | Keeps rows that match, as the field's kind of match compares. See [Filtering](filtering.md#filters) | | `-` and a filter column or scope | `?-votes=10`, `?filter[-votes]=10` | Keeps rows that don't match | | `sort` | `?sort=-votes,title` | Sorts; a leading `-` is descending. The key breaks ties | | `page` or `page[number]` | `?page=2` | The page; default `1` | | `perPage` or `page[size]` | `?perPage=50` | The page size; default `PER_PAGE`, at most `RESTIFY_MAX_PER_PAGE` when the application sets it | | `related` | `?related=user,comments.user`, `?related=user[name]` | Loads the relationships the repository lists, with a dot for nested ones and `[a\|b]` to pick columns. Other names are ignored. Show takes it too. See [Relationships](relationships.md) | | `include` | `?include=user` | The same as `related`, read only when `related` is absent | | `relatablePerPage` | `?relatablePerPage=5` | How many related models a list relationship loads for each record. See [Relationships](relationships.md#limiting-lists-with-relatableperpage) | | `filters` | `?filters=` | The [advanced filters](filtering.md#advanced-filters) | | `group_by` | `?group_by=user_id` | Groups by `groupable` columns. See [Grouping](filtering.md#grouping) | | `withMeta` | `?withMeta=true` | Adds each listed record's `meta`. See [Authorization](authorization.md#what-the-user-may-do-with-a-record) | Any other parameter is ignored, as are filters and sorts on columns the repository doesn't mark. ## A resource ```json { "id": "2", "type": "posts", "attributes": { "user_id": 1, "title": "Restify", "body": "APIs for humans and agents", "excerpt": "APIs for humans and...", "votes": 30, "featured": 0, "rating": "3.00", "published_at": "2026-01-03T12:30:00.000000Z", "created_at": "2026-01-03T12:00:00.000000Z" } } ``` `id` is the model's key as a string. `type` is the repository's `resource_type`, the model's table by default. `attributes` holds the repository's [fields](fields.md), in the order it lists them: the ones the view shows and the request may see. This is the example app's post as an admin sees it; a list leaves `body` out, and another user doesn't get `featured`. A shown resource also has `meta`, with what the user may do with it. See [Authorization](authorization.md#what-the-user-may-do-with-a-record). A listed resource has it only with `?withMeta=true`, and leaves `attributes` out when it shows no field. A request with `?related=` adds a `relationships` key. Each loaded relationship is a resource of the related repository, a list of them, or the related model's own JSON for one declared with `Related::raw`. See [Relationships](relationships.md#what-a-response-contains). ## A page ```json { "meta": { "current_page": 1, "from": 1, "last_page": 3, "path": "https://example.com/api/restify/posts", "per_page": 15, "to": 15, "total": 42 }, "links": { "first": "https://example.com/api/restify/posts?page=1", "next": "https://example.com/api/restify/posts?page=2", "path": "https://example.com/api/restify/posts", "prev": null, "filters": "/api/restify/posts/filters" }, "data": [resource, resource] } ``` As in Restify for PHP, there is no `last` link, a page link carries the page number alone, and `filters` is a path without the host. ## Errors | Status | When | Body | | --- | --- | --- | | `401` | The middleware found no user | `{ "message": "Unauthenticated." }` | | `403` | A request to the MCP server from a browser page on another origin that the CORS settings don't list for its path. See [MCP](mcp.md#calling-the-mcp-server-from-a-browser) | `{ "jsonrpc": "2.0", "error": { "code": -32600, "message": "The request's origin isn't allowed." } }` | | `403` | `authorize`, a policy, or the input's own check refused | `{ "message": "This action is unauthorized." }`, or another text of [Authorization](authorization.md#what-a-refusal-looks-like) | | `404` | No model has the key, or `query` leaves it out | `{ "message": "No query results for model [Post]." }` | | `404` | No action or getter has the key, or no route has the path | `{ "message": ".." }`, such as `Action not found.` | | `404` | The path's first part names no repository, such as `/api/restify/widgets` | `{ "message": "Repository widgets not found." }` (Restify for PHP answers `500`: a PHP bug) | | `422` | The input is invalid | `{ "message": "..", "errors": { "field": [".."] } }` | | `422` | `?group_by=` names a column that isn't `groupable` | `{ "message": "The column [..] is not allowed for grouping. Allowed columns are: .." }` | | `422` | `?filters=` isn't base64 of a JSON list or object | `{ "message": "..", "errors": { "filters": [".."] } }` (Restify for PHP answers `500`: a PHP bug) | A bulk request's field errors name the item by its position, such as `1.title`. See [Bulk operations](bulk.md#errors). An MCP tool returns an error as a tool result with `isError: true`, in the words of Laravel's MCP server. See [MCP](mcp.md#when-a-call-fails). ## Commands | Command | Does | | --- | --- | | `laravel restify:list` | Prints each repository, its endpoint and its columns, then its actions and getters | | `laravel restify:list --json` | Prints the same as JSON, with the MCP tool names. An action or getter the MCP server doesn't serve, such as one of a repository with no `const MCP`, has no tool: `-` in the table, `null` in the JSON | | `laravel restify:install` | Writes the two skills for AI coding agents to `.agents/skills` and `.claude/skills` | | `laravel restify:install --path ` | Writes them to another application directory | | `laravel restify:openapi` | Prints the [OpenAPI document](openapi.md) as JSON | | `laravel restify:openapi --output ` | Writes it to a file | | `laravel restify:import ` | Writes an application's Restify code from a PHP application's `restify:export` file (feature `import`). Takes `--check`, `--migrations`, `--force` and `--path`. See [Migrating from Restify for PHP](migrating-from-php.md#import) | --- # Testing - [Introduction](#introduction) - [Testing endpoints](#testing-endpoints) - [Testing authorization](#testing-authorization) - [Testing MCP tools](#testing-mcp-tools) - [Comparing with a PHP app](#comparing-with-a-php-app) - [Testing on SQLite](#testing-on-sqlite) - [What to test](#what-to-test) ## Introduction Restify's endpoints are ordinary routes, so you test them with the framework's HTTP tests, described in its `testing.md` guide. These examples use the `Post` repository from the other guides, behind an API token. The example app runs each one, in [`tests/guide_examples.rs`](https://github.com/BinarCode/laravel-restify-rust/blob/main/example/tests/guide_examples.rs). ## Testing endpoints Send requests as a user with `acting_as`, and assert on the JSON: ```rust use app::models::User; use laravel::testing::prelude::*; #[laravel::test] async fn a_post_is_stored_for_the_logged_in_user(app: Application) -> laravel::Result<()> { let taylor = User::factory().create().await?; app.post("/api/restify/posts") .acting_as(&taylor) .json(json!({ "title": "Hello", "votes": 3 })) .await .assert_status(201) .assert_json(json!({ "data": { "type": "posts", "attributes": { "title": "Hello", "votes": 3, "user_id": taylor.id } }, })); app.assert_database_has("posts", json!({ "title": "Hello", "user_id": taylor.id })) .await; Ok(()) } ``` `assert_json` matches part of the response, so name only the fields the test is about. An `id` in a response is a string: compare it with `post.id.to_string()`. To test a list, assert the order and the count: ```rust app.get("/api/restify/posts?sort=-votes&featured=true") .acting_as(&taylor) .await .assert_ok() .assert_json_count_at("data", 1) .assert_json(json!({ "data": [{ "id": post.id.to_string() }] })); ``` ## Testing authorization Test each rule from both sides: the user who may, and the user who may not. ```rust app.get("/api/restify/posts").await.assert_unauthorized(); app.get("/api/restify/posts").token("wrong-token").await.assert_unauthorized(); app.patch(format!("/api/restify/posts/{}", post.id)) .acting_as(&another_user) .json(json!({ "votes": 1 })) .await .assert_forbidden(); app.assert_database_has("posts", json!({ "id": post.id, "votes": 10 })).await; ``` Also assert that a client can't write a column the input doesn't declare: ```rust app.post("/api/restify/posts") .acting_as(&taylor) .json(json!({ "title": "Hello", "user_id": another_user.id })) .await .assert_json_path("data.attributes.user_id", taylor.id); ``` ## Testing MCP tools A tool call is a `POST` to the MCP server with a JSON-RPC message. The test must send `Accept: application/json, text/event-stream`, as every MCP client does, or the server answers `406`. `.json(..)` sets `Accept` to `application/json` only, so set the header after it. A small helper keeps that in one place. The server starts in `wrapper` mode, which lists five tools: `global-search` and the four wrapper tools. To call one tool per operation, such as `posts-store-tool`, make the test's app in `direct` mode: ```rust use app::models::User; use laravel::testing::TestRequest; use laravel::testing::prelude::*; use restify::{McpMode, RestifyConfig}; use serde_json::Value; pub trait Mcp { fn message(self, message: Value) -> TestRequest; } impl Mcp for TestRequest { fn message(self, message: Value) -> TestRequest { self.json(message) .header("accept", "application/json, text/event-stream") } } /// The app with its MCP server in `direct` mode. pub fn direct_mcp() -> Application { app::testing::configure() .with_config(|config, _| { config.section_mut::().mcp_mode = McpMode::Direct; }) .create() } fn call(tool: &str, arguments: Value) -> Value { json!({ "jsonrpc": "2.0", "id": 1, "method": "tools/call", "params": { "name": tool, "arguments": arguments } }) } #[laravel::test(app = direct_mcp)] async fn an_agent_creates_a_post(app: Application) -> laravel::Result<()> { let taylor = User::factory().create().await?; app.post("/mcp/restify") .acting_as(&taylor) .message(call("posts-store-tool", json!({ "title": "From an agent" }))) .await .assert_ok() .assert_json(json!({ "result": { "isError": false, "structuredContent": { "data": { "attributes": { "title": "From an agent" }, } } } })); Ok(()) } ``` A refused or invalid call still answers `200`. Assert on `result.isError` and on the text of the result: ```rust app.post("/mcp/restify") .acting_as(&taylor) .message(call("posts-store-tool", json!({ "title": "" }))) .await .assert_json_path("result.isError", true) .assert_json_path("result.content.0.text", "A post needs a title."); ``` ## Comparing with a PHP app If you are moving an app from Restify for PHP, you can check that the Rust app answers the same requests in the same way. A *cassette* is a JSON file that holds requests and what the PHP app answered to them. `restify::testing::replay` sends those requests to your Rust app and fails the test when any answer is different. Turn the module on in `Cargo.toml`: ```toml [dev-dependencies] laravel-restify = { version = "0.2", features = ["testing"] } ``` Then, in a test, load the rows the recording started from, read the cassette, and replay it: ```rust use laravel::testing::prelude::*; use restify::testing::{Cassette, replay, seed}; #[laravel::test] async fn posts_answer_like_php(app: Application) -> laravel::Result<()> { seed(include_str!("../restify-oracle/seeds/blog.json")).await?; let cassette = Cassette::from_json(include_str!("../restify-oracle/cassettes/errors.json"))?; replay(&app, &cassette, &[]).await; Ok(()) } ``` - The paths start from the test file, in `tests/`. `restify:record` writes the cassettes to `restify-oracle/cassettes`. - `seed` inserts the rows inside the test's transaction, so they are gone after the test. It reads JSON you write, a list of rows per table, as in the repository's [`oracle/seeds/blog.json`](https://github.com/BinarCode/laravel-restify-rust/blob/main/oracle/seeds/blog.json). - `replay` freezes the clock at the time the cassette was recorded. - The third argument lists differences you accept on purpose, such as an error message that names a PHP class. Build one with `Divergence::new(scenario, step, pointer, reason)`. The module has a few more helpers for recordings of a real application: | Item | Does | | --- | --- | | `sanctum_tokens::(&cassette)` | Makes a Sanctum token for each user the cassette's `{{token:..}}` placeholders name (also needs the `sanctum` feature) | | `cassette.with_tokens(&tokens)` | Puts those tokens in place of the placeholders | | `cassette.with_files(folder)` | Says where the files are that the cassette's steps upload | | `replay_mcp(&app, &cassette, recorded_at, served_at, &divergences)` | Replays the steps a PHP MCP server answered against this application's MCP server (also needs the `mcp` feature) | The test file that `restify:import` writes uses each one its recordings need: see [Migrating from Restify for PHP](migrating-from-php.md#import). A failing test prints one line per difference, such as `/body/data/0/attributes/title: PHP "A", Rust "B"`, followed by both full answers. The exact comparison rules and the cassette format are in `oracle/README.md` of the [Restify for Rust repository](https://github.com/BinarCode/laravel-restify-rust), where this crate's own copy of the check lives (`example/tests/oracle_*.rs`). ## Testing on SQLite With `refresh_database()`, each test borrows a copy of the database, a numbered file such as `storage/testing_1.sqlite`, and gives it back when it ends. In `laravel-rust` 0.1.6 and 0.2.0, a test gives its file back a moment before its connection to the file has closed. If the next test takes that file in that moment, it fails before its first line runs, at random and rarely, most often on a busy CI machine: ```text the application failed to boot: booting `laravel::db::provider::DatabaseServiceProvider` failed: the SQLite database is locked by another connection's write, and the busy timeout passed. [..] (Connection: sqlite, Driver: SQLite, SQL: DELETE FROM refreshed_database WHERE fingerprint = ?) ``` Raising `busy_timeout` doesn't help: SQLite reports this kind of lock at once, without waiting. What helps is to make each new connection ask for the write lock first, with `BEGIN IMMEDIATE`. SQLite does wait for that request, until the previous test's connection has closed. In a new application, the tests use the database that `.env` names, PostgreSQL by default, or the one in `.env.testing` when that file exists: `for_testing` then reads it instead of `.env`. So without either change below, the tests run on the application's own database. To run them on a SQLite file of their own, with the fix, add three lines to the starter's `src/testing.rs`, and the function `wait_for_the_previous_test` from the example app's file below: ```rust pub fn configure() -> ApplicationBuilder { crate::configure() .for_testing(env!("CARGO_MANIFEST_DIR")) .with_envs([ ("APP_ENV", "testing"), // .. the starter's other settings ]) .with_env("DB_CONNECTION", "sqlite") .with_env("DATABASE_URL", "sqlite://storage/testing.sqlite?mode=rwc") .with_config(|config, _| wait_for_the_previous_test(config)) .refresh_database() } ``` The application needs the `database-sqlite` feature in its `laravel-rust` line for that. The example app's whole `src/testing.rs` does the same, but lets `TEST_DATABASE_URL` pick another database, such as PostgreSQL on CI, and adds the statement only on SQLite, where it belongs: ```rust use laravel::Application; use laravel::foundation::ApplicationBuilder; pub fn create() -> Application { configure().create() } /// Tests run on SQLite unless `TEST_DATABASE_URL` names another database, such as PostgreSQL. pub fn configure() -> ApplicationBuilder { configure_with(crate::restify()) } /// [`configure`] with `restify` as the Restify provider, for a test with a repository of its own. pub fn configure_with(restify: restify::Restify) -> ApplicationBuilder { let database = std::env::var("TEST_DATABASE_URL").unwrap_or_else(|_| "sqlite://storage/testing.sqlite?mode=rwc".to_owned()); let connection = database.split(':').next().unwrap_or("sqlite").to_owned(); let sqlite = connection == "sqlite"; crate::configure_with(restify) .for_testing(env!("CARGO_MANIFEST_DIR")) .with_envs([("APP_ENV", "testing"), ("APP_DEBUG", "true")]) .with_env("DB_CONNECTION", connection) .with_env("DATABASE_URL", database) .with_config(move |config, _| { if sqlite { wait_for_the_previous_test(config); } }) .refresh_database() } /// Make each new SQLite connection wait until the test that used the database file before it /// has really closed its connection. /// /// Each test borrows a database file, a "slot", and writes in a transaction that never commits. /// When a test ends, the framework (`laravel-rust` 0.1.6 and 0.2.0) gives the slot back before that /// connection has closed: SQLx closes it on a thread of its own a moment later. If the next test /// takes the slot in that moment, its boot reads the slot and then deletes a row from it. SQLite /// can't make a connection that has already read wait for another connection's write lock, so the /// delete fails at once with "database is locked", whatever the busy timeout. It happened on CI, on /// a busy machine. /// /// `BEGIN IMMEDIATE` asks for the write lock before the connection reads anything, and SQLite /// waits for that one through the busy timeout (5 seconds by default), until the old connection /// closes and rolls back. The empty transaction then commits, so the test's own transaction /// begins as usual. Remove this when the framework closes a slot's connections before giving it /// back. fn wait_for_the_previous_test(config: &mut laravel::config::Config) { let database = config.section_mut::(); let name = database.default.clone(); if let Some(connection) = database.connections.get_mut(&name) { connection .init_sql .push(laravel::db::sqlx::SqlStr::from_static("BEGIN IMMEDIATE; COMMIT")); } } ``` The statement only waits; it changes nothing in the database. You can remove it once the framework closes a test's connection before it gives the file back. ## What to test A tool and its endpoint run the same code, so you don't need every test twice. A good set for a repository: - One test per endpoint for the usual case. - One test per rule in `authorize` and in the policy, from both sides. - One test that a column the client must not write stays unwritten. - One test of the tool list, when the input's descriptions matter to you. - One MCP test of a create, to prove the server is wired up. --- # Before You Go to Production - [Introduction](#introduction) - [The checklist](#the-checklist) - [Cap the page size](#cap-the-page-size) - [Let tokens expire](#let-tokens-expire) - [Share the rate limits between servers](#share-the-rate-limits-between-servers) - [Trust only your own proxies](#trust-only-your-own-proxies) - [Know the registration limits](#know-the-registration-limits) - [Choose who may call the API from a browser](#choose-who-may-call-the-api-from-a-browser) - [Turn debug mode off](#turn-debug-mode-off) - [Trust every host your clients use](#trust-every-host-your-clients-use) - [Limit how much `?related=` loads](#limit-how-much-related-loads) - [Know what your database decides](#know-what-your-database-decides) ## Introduction Restify's defaults copy Restify for PHP, so a PHP application's clients keep working after the move. Some of those defaults are open: they suit a laptop, not a public server. Go through this page once before the first deploy, and again before a PHP application switches to Rust. ## The checklist | Setting | Default | Set it to | | --- | --- | --- | | `RESTIFY_MAX_PER_PAGE` | No limit, as in PHP | The largest page a client needs, such as `100` | | `RESTIFY_TOKEN_TTL` | Tokens never expire, as in PHP | A number of minutes, such as `43200` for 30 days | | `CACHE_STORE` | `memory`, one store per process | `database` or `redis` | | Trusted proxies | None | Your load balancer's addresses | | CORS | Any origin under `api/*`, no cookies | Your frontend's origins | | `APP_DEBUG` | `true` in `.env.example` | `false` | | Trusted hosts | The host of `APP_URL` | Every host your clients use | | `RESTIFY_RELATED_MAX_DEPTH` and `RESTIFY_RELATED_MAX_PATHS` | `3` and `20` | Keep them, or lower them | ## Cap the page size A client chooses the page size with `perPage` or `page[size]`. Without a cap, `perPage=100000` loads 100,000 rows in one request. Restify for PHP has no cap by default either, and PHP clients may rely on that, so Restify for Rust keeps it. Set the cap in `.env`: ```ini RESTIFY_MAX_PER_PAGE=100 ``` A larger `perPage` then gets 100 rows. The cap also limits how many related rows a list loads for each relationship. See [Pagination](filtering.md#pagination). ## Let tokens expire A token from `POST /api/login` works until the user logs out, as in PHP. A stolen token works forever. Make tokens expire after a number of minutes: ```ini RESTIFY_TOKEN_TTL=43200 ``` See [Sanctum tokens](sanctum.md). ## Share the rate limits between servers Login and registration are throttled as in PHP: 6 logins a minute for one email from one IP address, 30 logins a minute from one IP address, and 6 registrations a minute from one IP address. PHP doesn't let you change these numbers, so Restify doesn't either. The counters live in the framework's default cache store. That store is `memory` unless `CACHE_STORE` says otherwise. The `memory` store belongs to one process and is emptied on each restart. With 4 servers, a client gets 4 times the limit, and a deploy resets it. Use a shared store: ```ini CACHE_STORE=redis ``` See the framework's [rate limiting guide](https://github.com/laravel/rust-framework/blob/0.x/docs/rate-limiting.md#cache-configuration). ## Trust only your own proxies The rate limits count by IP address. Behind a load balancer, every request seems to come from the load balancer's address, so all clients share one limit. Tell the framework which proxies to trust, in `src/app.rs`: ```rust .with_middleware(|middleware, _| { middleware.trust_proxies(["10.0.0.0/8"]); }) ``` Don't trust `"*"` unless your load balancer replaces any `X-Forwarded-For` header the client sent. Otherwise a client can pick its own IP address and skip the limits. See the framework's guide on [trusting proxies](https://github.com/laravel/rust-framework/blob/0.x/docs/middleware.md#trusting-proxies). ## Know the registration limits `POST /api/register` checks what PHP's `RestifyRegisterRequest` checks: | Key | Rules | | --- | --- | | `email` | Required, an email address, at most 255 characters, not already used | | `password` | Required, confirmed, at least 6 characters | | `name` | No rule, as in PHP | Restify keeps these rules so PHP clients keep working. A request body has the framework's size limit, so a `name` can't be endless. If your users table needs more, such as a length limit on `name`, serve your own register route instead of `Restify::auth`. See [Authentication](authentication.md). ## Choose who may call the API from a browser By default, the framework lets JavaScript on any website call routes under `api/*`, without cookies. Restify's routes are under `api/`, so any website can call them with a token it holds. If only your own frontend should, list its origins in `src/config/cors.rs`. See the framework's guide on [CORS](https://github.com/laravel/rust-framework/blob/0.x/docs/routing.md#cors). The MCP server refuses every other site's page, unless `src/config/cors.rs` lists the origin for its path: see [Calling the MCP server from a browser](mcp.md#calling-the-mcp-server-from-a-browser). ## Turn debug mode off With `APP_DEBUG=true`, a server error shows the error, its causes, the route and the request. Set it to `false` in production: ```ini APP_DEBUG=false ``` See the framework's [configuration guide](https://github.com/laravel/rust-framework/blob/0.x/docs/configuration.md). ## Trust every host your clients use In production, the framework answers `400` to a request whose `Host` header isn't the host of `APP_URL` or one of its subdomains. List every other host your clients use. See [Trust every host your clients use](migrating-from-php.md#trust-every-host-your-clients-use). ## Limit how much `?related=` loads Restify refuses a `?related=` or `include` chain deeper than `RESTIFY_RELATED_MAX_DEPTH` (3) and a request that names more than `RESTIFY_RELATED_MAX_PATHS` (20) relationships, with a `422`. Restify for PHP has no such limit. `0` turns a limit off. See [How deep, and how many](relationships.md#how-deep-and-how-many). ## Know what your database decides Restify runs on SQLite, PostgreSQL, MySQL and MariaDB. A few answers depend on the database, in Restify for PHP and in Restify for Rust alike, so they don't change when you move from PHP to Rust on the same database. Check them when you change databases: | What | SQLite | PostgreSQL | MySQL and MariaDB | | --- | --- | --- | --- | | `?search=` and upper and lower case | Ignores the case of A to Z | Ignores case | Follows the column's collation: the usual ones ignore case and accents, a `_bin` one doesn't | | Where `NULL` goes when sorting ascending | First | Last | First | | How text sorts | By the letters' codes: capitals first | By the database's locale | By the collation: the usual ones ignore case | | `?group_by=` a column that isn't the key | Works | `500` | `500` on MySQL (`ONLY_FULL_GROUP_BY`); works on MariaDB | To make the search ignore case on every database, set `RESTIFY_SEARCH_CASE_SENSITIVE=false`. See [Search](filtering.md#search). On MariaDB, start `DATABASE_URL` with `mariadb://`, not `mysql://`, so the framework writes MariaDB's SQL. On SQLite, put `journal_mode=wal` in the production `DATABASE_URL` too, if you turned on the write-ahead log: it is a setting of each environment's `.env`, not of the code. After the first write, `sqlite3 "PRAGMA journal_mode"` answers `wal`. See [Many token requests on SQLite](sanctum.md#many-token-requests-on-sqlite). --- # Troubleshooting - [Compiler errors](#compiler-errors) - [Unexpected responses](#unexpected-responses) - [Startup errors](#startup-errors) ## Compiler errors **"`NewPost` doesn't describe itself to AI agents" (the trait `Schema` is not implemented)** A repository's `Store` and `Update` types must derive `Schema`. Add `#[derive(Schema)]` under `#[laravel::input(..)]`: ```rust #[laravel::input(fills = Post)] #[validate(authenticated)] #[derive(Schema)] pub struct NewPost { /* .. */ } ``` **"`PublishPost` isn't an action or getter of `Post`" (the trait `CustomAction` is not implemented)** The type has no `impl CustomAction`, or it implements it for another model than the repository's. See [Actions and getters](actions.md#writing-an-action). **"type mismatch resolving `>::Target == Builder`"** `Custom::index` or `Custom::standalone` was given an action on one model, or `Custom::show` one on the list. Use `Custom::show` for `type Target = Post`, and the other two for `type Target = Builder`. See [Actions and getters](actions.md#listing-them-in-the-repository). **"Restify doesn't know how a `Status` looks in JSON" (the trait `Property` is not implemented)** A field of a `#[derive(Schema)]` struct, or a value a `Field` shows, has a type Restify can't describe. Implement `restify::Property` for it, which says how the type is described and written. See [Writing](writing.md#field-types) and [Fields](fields.md#how-each-type-is-written). **"no method named `without_mcp` found for struct `Restify`" (or `mcp`, `openapi`, `openapi_version`)** The method belongs to a Cargo feature that is turned off. `mcp` and `without_mcp` need the `mcp` feature, and `openapi` and `openapi_version` need the `openapi` feature. Turn the feature on in `Cargo.toml`, or remove the call. See [Choosing features](installation.md#choosing-features). **"serde doesn't know this `rename_all` rule"** `#[derive(Schema)]` reads serde's own `rename_all` rules, such as `camelCase`, so check the spelling. **"`..` isn't a gate" in `can_see`** `can_see` takes a `bool`, or an async function from the request: `async fn is_admin(request: &Request) -> laravel::Result`. A function that also takes the model can't be a gate, because a gate runs once for a request. Use `Field::computed_with` for a value that depends on the model. See [Fields](fields.md#showing-a-field-to-some-users). **"`NewPost` can't be the `Store` or `Update` input of a repository of `Post`" (the trait `Fills` is not implemented)** The struct lacks `#[laravel::input(fills = Post)]`, names another model, or has a field whose type isn't `Clone`. The input fills the write and is then lent to the `creating` or `updating` hook, so it is cloned field by field. **"method `creating` has 2 parameters but the declaration in trait has 3"** `creating` and `updating` get the validated input as their second argument: `creating(create, input: &NewPost, request)`. See [Writing](writing.md#setting-columns-the-client-cant). **"method `uri_key` has an incompatible type for trait"** `uri_key` returns a `String`: `"articles".to_owned()`. **The trait bound `Column: Relation<_>` is not satisfied, in `Related::raw` or `Related::through`** Both take a relationship, such as `Post::user`, not a column such as `Post::title`. Declare the relationship on the model with `#[belongs_to]`, `#[has_many]` or another relationship attribute first. A `#[morph_to]` relationship isn't supported. See [Relationships](relationships.md). **"type mismatch resolving `<.. as Relation>::Related == ..`", in `Related::through`** The repository in `Related::through::` must serve the relationship's model: `Post::user` holds a `User`, so it needs a repository whose `type Model = User`. **"`HasMany` isn't a relationship field holding `User` models"** The closure of `Related::through` must return the field of the same relationship, such as `|post| &post.user` for `Post::user`. See [Relationships](relationships.md#declaring-the-relationships-clients-may-load). **The `ValidatesRequest` trait is not implemented** The input struct must say who may submit it: add `#[validate(authenticated)]` or `#[validate(anyone)]`. **"... isn't a many-to-many relationship of `Team` to `Note`" (the trait `ManyRelation` is not implemented)** `Related::many` only takes a `#[belongs_to_many]`, `#[morph_to_many]` or `#[morphed_by_many]` relationship. For any other kind, use `Related::through`. See [Relationships](relationships.md#many-to-many-relationships-clients-can-change). **Errors inside the `laravel-rust-database` crate when building a package or a workspace** The framework's `database` feature only compiles together with a driver. Enable `database-postgres`, `database-mysql` or `database-sqlite` on `laravel-rust` in the application. ## Unexpected responses **Requests with a token, or creates and updates, get slow on SQLite when many come at once** On SQLite, each write locks the whole database file, and other requests wait for it. Turn on SQLite's write-ahead log: add `journal_mode=wal` to `DATABASE_URL`, such as `sqlite://database/database.sqlite?mode=rwc&journal_mode=wal`. See [Many token requests on SQLite](sanctum.md#many-token-requests-on-sqlite). **A deleted token still works for a while** `SANCTUM_CACHE` is set, so the guard remembers accepted tokens for that many seconds. Delete a token with `AccessToken::delete`, which forgets it at once, or leave the setting out. See [Remembering tokens](sanctum.md#remembering-tokens). **`429 Too Many Requests` from `POST /api/login`, `/api/register`, `/api/forgotPassword`, `/api/resetPassword` or `/api/verify/..`** The client went over PHP's limits: 6 logins a minute for one email from one IP address, 30 logins a minute from one IP address, and 6 a minute from one IP address for each of the other routes. Wait for the seconds in the `Retry-After` header. See [Too many tries](authentication.md#too-many-tries). **`POST /api/forgotPassword` answers `200`, but no email arrives** Forgot password answers `200` whatever happens, so nobody can use it to find out who has an account. Check, in this order: 1. No user has that email. The answer is the same on purpose. 2. A reset email went to the same address less than a minute ago. A second one isn't sent. 3. The email couldn't be rendered or sent. The error is in the log. Turn on the framework's `minijinja` feature, which renders the email, and set its `MAIL_*` settings. See [Changing the emails](authentication.md#changing-the-emails). 4. The email waits in the queue. Run a queue worker, or set `QUEUE_CONNECTION=sync`. **`422` "The url host is not allowed." from `POST /api/forgotPassword`** The request sent its own `url`, and its host is neither the host of `RESTIFY_PASSWORD_RESET_URL` nor of `FRONTEND_APP_URL` (`APP_URL` when that is not set). Set `FRONTEND_APP_URL` to your frontend's address. See [Forgot and reset password](authentication.md#forgot-and-reset-password). **`400` "Provided invalid token." from `POST /api/resetPassword`** The token is wrong, was used already, or is older than 60 minutes. A newer reset email also replaces the token of the one before. Ask for a new link. **A verification link sends the browser to `..?success=false&message=Invalid+or+expired+verification+link.`** The link is older than 60 minutes, or was changed, or was signed with another `APP_KEY`. Links that PHP emailed only work while `APP_KEY` is the same as PHP's. The signature also covers the link's host, so the link must reach the server on the same host it names. See [Verifying emails](authentication.md#verifying-emails). **Every request answers `400` with `Bad request.` in production, but works locally** The request's `Host` is neither the host of `APP_URL` nor one of its subdomains. In production, Laravel for Rust refuses such a request before Restify sees it. The `local` and `testing` environments don't check. Laravel for PHP checks no host unless the application asks it to, so this often shows up right after a move from PHP. Set `APP_URL` to the address clients use, or list every host with `middleware.trust_hosts([..])` in `src/app.rs`. See [Trust every host your clients use](migrating-from-php.md#trust-every-host-your-clients-use). **`422` with "`..` goes 4 relationships deep, and at most 3 are allowed" or "The request names 21 relationships"** The `?related=` (or `include`) of the request goes deeper than `RESTIFY_RELATED_MAX_DEPTH` (3 by default), or names more relationships than `RESTIFY_RELATED_MAX_PATHS` (20 by default). Ask for the deeper ones in a second request, starting from the related repository, or raise the limit. See [How deep, and how many](relationships.md#how-deep-and-how-many). **A relationship shows fewer rows than the database has, or `null`, or an attach answers `404` for a row that exists** The related repository's `Repository::query` hides those rows from this request. A `through` relationship, and an attach, detach or sync, reach only the rows that the related repository's own endpoints reach. To show them, widen that `query` for the `Action` it gets. See [Who can see a relationship](relationships.md#who-can-see-a-relationship). **A repository's middleware refuses an MCP tool, a nested route, the profile or the global search, not only its own routes** A repository's `middleware()` runs wherever its operations are reached: its own routes, its MCP tools, a nested route of another repository, the profile, and the global search (`/api/restify/search` and the `global-search` tool) when the repository is globally searchable. A refusal answers with the middleware's status and `message`. In the global search, one repository's refusal refuses the whole search, as in Restify for PHP. Through MCP, a `403` shows its message, and other statuses show as an internal error. See [Where the middleware run](repositories.md#where-the-middleware-run). **`DELETE /{repository}/{id}/field/{field}` answers `403` although the user may update the record** The field's `can_update` refuses the user, or its `readonly_when` makes it read-only for them. Deleting a file writes the field, so it asks the same gates as a full update. See [Replacing and deleting files](files.md#replacing-and-deleting-files). **Every request answers `403`** The repository has no `authorize` method, or its `match` doesn't allow `Action::AllowRestify`, which every request is asked for first, or the action itself. Restify refuses everything by default. See [Authorization](authorization.md). **`403` with `Unauthorized to view repository posts. Check "allowRestify" policy.`** The repository's `authorize` refused `Action::AllowRestify`, which every request is asked for first. Allow it for the users who may use the repository. See [Authorization](authorization.md#deciding-who-may-do-what). **A list has fewer rows than `per_page`, but `meta.total` counts more** `authorize` refused `Action::Show` for some rows, so the list left them out after counting them, as Restify for PHP does. To leave them out of the count too, filter them in `Repository::query`. See [Authorization](authorization.md#rows-a-list-leaves-out). **`404` with `Repository widgets not found.`** The first part of the path names no repository, such as `/api/restify/widgets`. Check the repository's `uri_key` and that the provider registers it with `Restify::repository`. Restify for PHP answers this with a `500` `Server Error`, which is a PHP bug. **`422` with `` `filters` must be a JSON list encoded in base64 ``** `?filters=` isn't a JSON list encoded in base64. Build it with `btoa(JSON.stringify([{"key": "status", "value": "draft"}]))` in JavaScript, or `base64_encode(json_encode([...]))` in PHP. See [Advanced filters](filtering.md#advanced-filters). Restify for PHP answers this with a `500`, which is a PHP bug. **Every request answers `401`** The middleware given to `Restify::new().authenticate(..)` found no user. Check that the request sends `Authorization: Bearer ` and that the guard looks the token up the way it's stored. In a test, use `.acting_as(&user)`. **`403` with `Unauthorized to use the route /api/restify/bulletins. Check prefix.`** The repository has its own `prefix`, so it is served only under that path, such as `/api/v1/bulletins`. Send the request there. Restify for PHP answers the same. See [Repositories](repositories.md#serving-under-another-prefix). **A public repository answers `500` to a guest** On a public repository's list, show and getters no token is read, so `request.user()` fails in `authorize` or in a field's gate. Check `request.authenticated()` first and treat a guest as not allowed. See [Repositories](repositories.md#public-repositories). **`401` with `Unauthorized to view restify.`** The application's gate middleware refused the user, as Restify for PHP's `viewRestify` gate does. See [Authorization](authorization.md#refusing-some-users-everywhere). **`POST /api/login` or `/api/register` answers `500`: "no session guard logs in `User`"** These routes have no guard, because the client has no token yet. A field's `can_see` gate or a policy called `request.user()`, which fails on such a route. Check `request.authenticated()` first and treat a guest as not allowed. See [Authentication](authentication.md#fields-and-gates-on-guest-routes). **`POST /api/logout` answers `200`, but the PHP application answered `500`** This is on purpose. Restify for PHP deletes the token and then answers `500` "Server Error", which is a bug in PHP. Restify for Rust deletes the token and answers `200` with `{"message": "Successfully logged out."}`. See [Authentication](authentication.md#register-login-and-logout). **`500`: "Sanctum has no settings"** The Sanctum guard is used, or a login creates a token, but the guard isn't a provider. Add `providers.add(restify::auth::Sanctum::::new())` in `src/app.rs`. **`500`: "A Sanctum token can't be created for the User with key `..`"** Sanctum's `tokenable_id` column holds integers, so a user model whose key is a UUID or text can't have Sanctum tokens. **A deleted post still shows in `?related=posts`** `soft_deletes` covers the repository's own queries, not relationships declared on other models. Add `filter = Post::deleted_at.is_null()` to the relationship. See [Soft deletes](soft-deletes.md#relationships-on-other-models). **A filter or a sort has no effect** The list ignores a parameter it doesn't know, as Restify for PHP does. Check that a field of the repository marks the column `matchable` or `sortable`, or that a scope has the name. The parameter is the column's name, not the field's `label`. A repository with no sortable field sorts by its key only under its table's name, such as `?sort=tags.id`. See [Filtering](filtering.md). **A filter keeps no rows, or the wrong ones** Each kind of match compares in its own way, as in Restify for PHP. A `Text` filter is an exact match, not "contains": use `?search=` for that. An `Integer` filter reads only the leading number, so `?votes=10,20` means 10; use `MatchKind::Array` for a list. A value that isn't of the column's type keeps no rows, such as `?author_id=-1` on a `u64` column. See [Filtering](filtering.md#filters). **`422`: "The column [title] is not allowed for grouping"** The column isn't marked `groupable`. Mark it with `Field::groupable()`, or `Field::query_only(..).groupable()` for a column no response shows. See [Grouping](filtering.md#grouping). **An advanced filter is ignored** Its `key` names no `Scope::advanced` filter of the repository, or the filter's `can_see` gate refuses the user. Check the names in `GET /api/restify//filters`. **"`PostRepository` isn't globally searchable" (the trait `GlobalSearch` is not implemented)** `Restify::global_search::()` needs `impl GlobalSearch for R {}`. Its items have defaults, so the empty block is enough. See [Global search](filtering.md#global-search). **"`global_search` was called for the .. repository before `repository` served it"** List the repository with `.repository::()` first, then add it with `.global_search::()`. **`?related=` answers `200` but the relationship is missing** A name the repository doesn't list is ignored, as in Restify for PHP. Check that `Repository::related` lists it and that the client uses the field's name. A `through` relationship is also left out when the related repository refuses `Action::AllowRestify` to the request, or when its `can_see` gate fails. For a nested name such as `comments.user`, the related repository must list `user`. See [Relationships](relationships.md). **`403`: "You are not authorized to see the user relationship"** The related repository refuses `Action::Show` for the one model a `through` relationship holds, such as a post's author. Allow it in that repository's `authorize`, or don't list the relationship. See [Relationships](relationships.md#who-can-see-a-relationship). **`?search=` returns the whole list** No field of the repository is `searchable`, so the term is ignored, as in Restify for PHP. `?search=0` is ignored too. **A create ignores a field the client sent** The `Store` struct doesn't declare the field, which is how mass assignment is prevented. Add the field if a client may write it, or set the column in `creating` if the server decides it. See [Writing](writing.md). **A `PATCH` clears columns the request didn't send** A field of the `Update` struct is an `Option`. Declare it as `Sometimes`, or `Sometimes>` when `null` may clear it. **A resource has no attributes, or lacks a column** A response shows only the fields `Repository::fields` lists. Add `Field::new(Post::column)`. A field with `hide_from_index` is left out of lists and of the answers to a create or an update, and a field with `can_see` is left out for the requests that don't pass its gate. See [Fields](fields.md). **A column shows up in responses that shouldn't** Remove its field from `Repository::fields`, or keep it for filtering with `Field::query_only`. To show it to some users only, give the field a `can_see`. A relationship declared with `Related::raw` is different: it shows the related model as serde writes it, so there `#[serde(skip)]` on the model's field hides a column. Use `Related::through` to show the related repository's fields instead. See [Relationships](relationships.md#raw-relationships-and-the-models-json). **`403` from `/posts/bulk`** The repository's `authorize` doesn't allow `Action::StoreBulk`, `Action::UpdateBulk` or `Action::DeleteBulk`. They are separate from the single actions. See [Bulk operations](bulk.md#allowing-bulk-requests). **`perPage` returns more rows than you want to allow** A request may ask for any page size unless the application sets `RESTIFY_MAX_PER_PAGE`. See [Filtering](filtering.md#pagination). **`422` from a bulk request: "Send at most 100 items at once"** The array holds more than the repository's `MAX_BULK` items. Split the request, or raise `MAX_BULK`. **`422` from a bulk request: "Send the items as a JSON array." or "Send at least one item."** The body of a bulk request is a JSON array with at least one item, not an object. See [Bulk operations](bulk.md). **`422` from a bulk update: "The 0.title field is required."** A bulk update is a full update, like `PUT`: every field with a `required` rule must be in every item. Send the field in each item, or use `PATCH` on each record to change only some fields. **A bulk request saved nothing** That is on purpose: Restify checks every item before it writes any, and one failed item stops them all. A field error names the item to fix by its position, starting at `0`, such as `1.title`. **`422` from `PUT`: "A post needs a title." though only `votes` was sent** `PUT` and `POST /api/restify/posts/1` are full updates, so every field with a `required` rule must be sent. Use `PATCH` to change only the fields you send. See [Writing](writing.md#the-update-input). **A field sent in a create or an update was not saved** A write gate refused it: `can_store`, `can_update`, `can_patch` or `readonly_when`. The request still succeeds, without that field. See [Writing](writing.md#fields-only-some-users-may-write). Note that `can_update` isn't asked by `PATCH`. **"The posts field `featured` has a write gate, so Restify removes `featured` from the input of a request the gate refuses, but `app::models::NewPost` requires `featured`"** The application refuses to start. A field with a write gate is removed from the input when the gate refuses, so the input struct must allow it to be missing. Declare the field as `Sometimes`, such as `pub featured: Sometimes`. **An action answers `404` "Action not found." (or a getter "Getter not found.")** The request names no action listed where it was sent. Check three things. The key: `?action=` must be the action's `uri_key`, which defaults to its `NAME` in kebab-case, such as `publish-posts-action`. The place: an action listed with `Custom::show` runs at `/posts/{id}/actions`, and one listed with `Custom::index` at `/posts/actions`. The method: an action answers `POST` and a getter `GET`. `GET /api/restify/posts/actions` lists what a request may run. The message is PHP's, so it doesn't say which keys exist. **An action answers `403` "Not authorized to run this action."** Its `can_run` refused, or it has none, which refuses everyone by default. For an action on the list, one refused post refuses the whole request. See [Actions and getters](actions.md#who-may-see-and-run-one). **An action answers `403` "You don't have permission to run this action."** Its `can_see` hides it from this request. **An action answers `422` "The repositories field is required."** An action listed with `Custom::index` runs on the posts the client names: send `{ "repositories": [1, 2] }` or `{ "repositories": "all" }`. For an action that runs on no post in particular, list it with `Custom::standalone`. **A model answers `404` although it exists** `Repository::query` leaves it out, or the key in the URL isn't of the key's type. **The MCP server answers `406` or `415`** The request isn't one the MCP specification allows. A client must send `Accept: application/json, text/event-stream` (`406` without it) and `Content-Type: application/json` (`415` without it). MCP clients do this for you. In a test, `.json(..)` sets `Accept` to `application/json` only, so add the header after it, as [Testing](testing.md#testing-mcp-tools) shows. **The MCP server answers `403` with "The request's origin isn't allowed."** The request came from a browser page on another origin, such as a frontend on `http://localhost:5173` calling an API on `http://localhost:8000`. List that origin in `src/config/cors.rs`, and add the server's path, such as `mcp/*`, to its `paths`. `Allowed::Any` doesn't count: name each origin. See [Calling the MCP server from a browser](mcp.md#calling-the-mcp-server-from-a-browser). **`POST /teams/1/attach/users` answers `400` with "Missing BelongsToMany or MorphToMany related for [users]"** Three things cause it: - The team repository's `related` doesn't list `users` with `Related::many`. `Related::through` shows a relationship but doesn't let clients change it. - The related repository's `authorize` refuses `Action::AllowRestify` for this request. - The relationship's `can_see` refuses this request. See [Relationships](relationships.md#attach-detach-and-sync). **An attach, detach or sync answers `403`** The parent's `authorize` refused `Action::Attach`, `Action::Detach` or `Action::Sync` with the relationship's name, such as `Action::Attach("users")`. A `match` that doesn't list the question refuses it. To decide for each related model, read `restify::relating::(request)`. See [Relationships](relationships.md#who-may-attach-detach-and-sync). **`GET /posts/1/comments` answers `403` with "Eager field missing from the parent [posts] related fields."** The last part of the URL must be the related repository's name, such as `comments`, and the parent's repository must list that relationship with `Related::through` or `Related::many`. A `Related::raw` relationship has no nested routes. The same answer comes when the related repository refuses `Action::AllowRestify`, or the relationship's `can_see` refuses. See [Relationships](relationships.md#nested-routes). **`POST /teams/1/users` answers `400` with "Creating [users] through [teams] is only supported for has-one and has-many relations"** A create through a parent only works for `#[has_one]`, `#[has_many]`, `#[morph_one]` and `#[morph_many]`. To add an existing user to a team, use `POST /teams/1/attach/users`. A has-many relationship also answers this when the related model doesn't declare the `#[belongs_to]` back to the parent. **An agent doesn't see a field, or sends the wrong thing** Look at what the agent sees: `tools/list` on the MCP server in `direct` mode, or `get-operation-details` in `wrapper` mode, or the test in [Testing](testing.md#testing-mcp-tools). A field needs a doc comment to have a description, and a rule needs to be a `#[validate(..)]` attribute to appear in the schema. **The MCP server lists only five tools** That is `wrapper` mode, the default: `global-search` and four tools that find and run the operations. The agent finds each repository's operations with `discover-repositories`, then runs them with `execute-operation`. To list one tool per operation instead, set `RESTIFY_MCP_MODE=direct`. See [Choosing a mode](mcp.md#choosing-a-mode). **`global-search` finds nothing, or leaves out a repository** The tool searches only the repositories added with `.global_search::()`, the same ones `GET /search` searches. A repository's `const MCP` doesn't matter here. Add the repository after `.repository::()`. See [Global search](filtering.md#global-search). **An agent gets `Tool [posts-store-tool] not found.`, or `INVALID_REPOSITORY` or `INVALID_OPERATION`** The server doesn't serve that operation to this user. When the message starts with `Unknown operation_type` or `Unknown action` (or `Unknown getter`), it lists the valid names: use one of them. Otherwise, check, in this order: 1. The repository sets `const MCP`. Without it, the repository has no tools. 2. `const MCP` allows the operation, such as `store: true`. `McpTools::INDEX` allows the list only. 3. `RESTIFY_MCP_READ_ONLY` isn't `true`. Read-only mode drops every tool that writes, and every action. 4. For an action or getter, its `can_see` allows this user. 5. The tool name fits the mode: `posts-store-tool` exists in `direct` mode only. In `wrapper` mode, call `execute-operation`. See [Letting agents use a repository](mcp.md#letting-agents-use-a-repository). **An action run through MCP changes no record** The tool reads the records from `repositories`, not from the `resources` its schema lists, as in Restify for PHP. Send `{ "repositories": [1, 2] }`. See [Behaviour kept from Restify for PHP](mcp.md#behaviour-kept-from-restify-for-php). **A relationship is missing from what an MCP tool returns** The related repository doesn't set `const MCP`. A tool leaves out the relationships of repositories that agents may not use. Set `const MCP` on that repository, even to `Some(McpTools::INDEX)`. **A file was sent, but the column didn't change** Check these, in order: - The request was a `PATCH`. `PATCH` reads a JSON body only, as in Restify for PHP. Send the file with `PUT`, or `POST /api/restify/{repository}/{id}`. - The body wasn't `multipart/form-data`. Only that body can hold a file. - The input struct has no `UploadedFile` field named like the column, or the repository lists the column with `Field::new` instead of `Field::file`. See [Files and images](files.md#declaring-a-file-field). - The request was a bulk request. Bulk requests ignore file fields, as in Restify for PHP. **`422` with "The avatar field is invalid." on a file field** The client sent text, such as a URL, instead of a file. A file field takes a file in a `multipart/form-data` body. To store URLs, add a plain text field with the `url` rule. A field with a rule answers with that rule's message instead, such as "The cover field must be an image." for `#[validate(image)]`. An MCP tool call that names a file field gets the same answer. Tool arguments are JSON, which can't hold a file, so the tools don't list file fields. Upload the file with an HTTP request instead. See [Files and images](files.md#ai-agents-and-bulk-requests). **`404` with an empty message from `DELETE /api/restify/{repository}/{id}/field/{field}`** The field isn't a file field of the repository, or it is `.deletable(false)`. The name in the path is the column's name, such as `avatar`. ## Startup errors **"The documents field `title` calls `path`, which only a file field has"** `disk`, `path`, `store_as`, `store_original_name`, `store_size`, `prunable`, `deletable` and `url` only work on a field made with `Field::file` or `Field::image`. Change `Field::new` to one of them, or remove the call. **"The `users` relationship can't show the pivot `role`"** `Related::pivot` needs a relationship declared with `Related::many`, and the field's type must name the join row that has the column, such as `BelongsToMany`, not `BelongsToMany`. See [Relationships](relationships.md#many-to-many-relationships-clients-can-change). **"Two Restify repositories are both named `posts`"** Two repositories serve models with the same table, or return the same `uri_key`. Override `uri_key` on one of them. **"The posts action `Publish Posts` needs a kebab-case key"** or **"has two actions with the key `publish`"** Change the `CustomAction::uri_key` or the `NAME` the message names. A key is lowercase letters, digits and dashes, unique among the repository's actions, and among its getters. **"The posts repository shows two fields named `title`"** Two fields of one view have the same name. Remove one from `Repository::fields`, or rename one with `Field::label`. **"The posts field `excerpt` is computed, so clients can't search, filter, sort or group by it"** A computed field has no column to query. Remove `searchable`, `matchable`, `sortable` and `groupable` from it, or write a [scope](filtering.md#scopes). **"The posts field `status` is `matchable`, but its column's type doesn't say how to compare it"** **"The posts field `status` is `matchable_as(MatchKind::Text)`, but its column's type can't read a filter's value"** The column's type has no `Property::parse`, so no filter value could ever equal a row. Set `Property::MATCH` and `Property::parse` for the type, or filter with a `Scope::matching` in `Repository::scopes`. Every integer type, `u64` keys included, `String`, `Uuid`, `Ulid`, the floats, `Decimal`, `bool`, `Timestamp` and `civil::Date` already can be read. See [Filtering](filtering.md#filters). **"The posts getter `stats` takes input"** A getter answers `GET`, which has no body to send input in. Set its `type Input = restify::NoInput`, or list it in `actions` instead. **A test on SQLite fails at random, before its first line, with "the SQLite database is locked by another connection's write" and `SQL: DELETE FROM refreshed_database`** The test started while the test before it was still closing its connection to the same test database. The cause is in `laravel-rust` (0.1.6 and 0.2.0), not in your test. Make each new test connection wait for the old one, as [Testing on SQLite](testing.md#testing-on-sqlite) shows. ## Import errors `restify:import` checks the whole manifest before it writes anything. Each of these errors means nothing was written. **"The manifest has names that give no Rust name, or the same one"** A name in the manifest can't become a Rust name. Either it has no ASCII letter or digit, such as a column called `--`, or two names turn into the same one. Examples: two models called `Post` in different namespaces, or the columns `first-name` and `first_name`. The error lists each one. Rename it in the PHP application, then export again with `php artisan restify:export`. **"The import would write `…`, which isn't a plain path inside the application"** A path the import built points outside the application's folder. That only happens when the manifest was edited by hand. Export it again, and don't edit it. **"Nothing was written: … The application's files are as they were before the import"** A file couldn't be written, for example because a folder is read-only, or a folder has the same name as a file the import writes. The import put back every file it had already changed. Fix the cause and run the import again. **"The manifest's `app.sanctum.expiration` is … which isn't a number of minutes"** Sanctum's token lifetime, `config('sanctum.expiration')`, must be a number of minutes, or `null` for tokens that don't expire. Fix it in the PHP application, then export again. --- # Migrating from Restify for PHP - [Introduction](#introduction) - [With an AI coding agent](#with-an-ai-coding-agent) - [How it works](#how-it-works) - [Export the PHP application](#export-the-php-application) - [Create the Rust application](#create-the-rust-application) - [Check what won't migrate](#check-what-wont-migrate) - [Record what PHP answers](#record-what-php-answers) - [Import](#import) - [Testing against a copy of the database](#testing-against-a-copy-of-the-database) - [Working through the tasks](#working-through-the-tasks) - [Reading a replay failure](#reading-a-replay-failure) - [When PHP answers wrongly](#when-php-answers-wrongly) - [A difference on one database only](#a-difference-on-one-database-only) - [What the import writes](#what-the-import-writes) - [Cutting over](#cutting-over) ## Introduction This guide moves an API built with Restify for PHP to Restify for Rust, so that it answers every request the same way, only faster. It is one command plus a list of tasks, not one command alone. The import writes everything it can translate. Everything it can't, such as the body of a policy method, becomes a numbered task in `MIGRATION.md`, with a closed stub in the code until the task is done. You know you are done when the Rust application replays every recording of what PHP answered, and gets the same answer. ## With an AI coding agent The skill `restify-migrate` takes an agent through this guide step by step, starting in the PHP application. Install the helper package there and write the skill into the application: ```bash composer require --dev binarcode/laravel-restify-rust-migrate php artisan restify:rust-install ``` Then tell the agent: "migrate this application to Rust with the restify-migrate skill". In Claude Code you can type `/restify-migrate` instead. The agent exports the application, creates the Rust application next to it, and stops to ask you only what a person must decide: whether to go on after the list of what won't migrate, which users to record as, and which database to record on. Record on a copy of the database, never production. `restify:rust-install` writes the skill to `.agents/skills/restify-migrate`, which agents share, and the same files to `.claude/skills/restify-migrate`, because Claude Code reads skills only from there and only those become slash commands. It lists the skill in `AGENTS.md` if the application has one, and changes nothing else. Later, `restify:install` writes the same skill into the Rust application. ## How it works | Step | Where | Command | | --- | --- | --- | | 1. Describe the PHP application | PHP | `php artisan restify:export` | | 2. Create the Rust application | Rust | `git clone --branch 0.x https://github.com/laravel/rust.git my-api` | | 3. List what won't migrate | Rust | `restify:import --check` | | 4. Record what PHP answers | PHP | `php artisan restify:record` | | 5. Generate the Rust code and its tasks | Rust | `restify:import ` | | 6. Do the tasks until the recordings replay | Rust | `cargo test --test restify_parity` | ## Export the PHP application The two PHP commands, `restify:export` and `restify:record`, come in a small Composer package. Install it in the PHP application, as a development dependency. It needs Restify for PHP 10.4.59 or later, and Laravel 12 or 13: ```bash composer require --dev binarcode/laravel-restify-rust-migrate ``` Then run: ```bash php artisan restify:export --pretty ``` It writes `restify-manifest.json`: the repositories, their fields, filters, relationships and policies, the models and their database columns, the routes, and the parts of the configuration Restify reads. It never runs your closures and never exports a secret. The package's `docs/manifest.md` lists everything in it: https://github.com/BinarCode/laravel-restify-rust/blob/main/php/docs/manifest.md. The `issues` list at the end of the file names each part the export couldn't read, such as a `fields()` method that needs a logged-in user. The import can't translate those parts. Fix them in PHP and export again, or plan to write them by hand. ## Create the Rust application Copy the official starter application. This needs only Git and Rust 1.99 or later: ```bash git clone --depth 1 --branch 0.x https://github.com/laravel/rust.git my-api cd my-api rm -rf .git && git init cargo run -- key:generate ``` `key:generate` creates `.env` from `.env.example` and writes a new `APP_KEY`. With the new Laravel CLI installed (the framework's `installation.md`), `laravel new my-api --rust` does all of this in one step. Laravel Herd's `laravel` command is an older installer, without `--rust`: `laravel --version` must start with `Laravel CLI`. The starter's `0.x` branch is on `laravel-rust` 0.2, which Restify 0.2 needs ([Framework versions](installation.md#framework-versions)). Then add Restify to `Cargo.toml`, with the features the migration uses: ```toml [dependencies] laravel-restify = { version = "0.2", features = ["sanctum", "import"] } [dev-dependencies] laravel-restify = { version = "0.2", features = ["sanctum", "import", "testing"] } ``` The generated code also uses `serde` (with its `derive` feature) and `serde_json`. The starter already has both, so add them only if they are missing. Use the database the PHP application uses. The starter's `laravel-rust` line has `database-postgres`: replace it with `database-sqlite` or `database-mysql` (for MySQL and MariaDB) if PHP uses one of those, and set `DB_CONNECTION` and `DATABASE_URL` in `.env`. For MariaDB, start `DATABASE_URL` with `mariadb://`, so the framework writes MariaDB's SQL. When the feature is missing, `restify:import` adds a task that says which one to add. While you migrate, point the Rust application at the copy you record on ([Record what PHP answers](#record-what-php-answers)), never at PHP's real database. Point it at PHP's database only when you cut over. ```ini # SQLite: the full path of the copy. `mode=rw` stops with an error if the path # is wrong, instead of creating a new empty file. DB_CONNECTION=sqlite DATABASE_URL=sqlite:///var/www/php-app/database/record.sqlite?mode=rw # PostgreSQL DB_CONNECTION=postgres DATABASE_URL=postgres://user:password@127.0.0.1/php_db_record # MySQL (for MariaDB, start the URL with mariadb://) DB_CONNECTION=mysql DATABASE_URL=mysql://user:password@127.0.0.1/php_db_record ``` Restify needs one exact release of the framework, and says so in its `Cargo.toml`: Restify 0.2 requires `laravel-rust = "=0.2.0"`. The starter's `laravel-rust = "0.2"` accepts it, so Cargo builds that release. Restify and the application must be on the same minor version of the framework: Cargo never moves an application from 0.1 to 0.2 or back, and a mix fails to build. The table in [Framework versions](installation.md#framework-versions) says which Restify goes with which framework. To see the version in use, run `cargo tree -i laravel-rust`. `restify:import --migrations` keeps MySQL's and MariaDB's column types: an `unsigned` integer is read into a Rust type that holds every value it can have (a `tinyint unsigned` is an `i16`) and stays `unsigned` in the migration; an `enum(..)` keeps its values in the migration and gets a `one_of` rule when PHP has none; a `year` is an `i32`; a `bit(1)` is a `bool`; a MariaDB `json` column, which MariaDB reports as `longtext`, is JSON when the model casts it to `array` or `json`. An index keeps PHP's name when it isn't the usual one, and a name longer than MySQL's 64 characters is shortened. For a PHP application on SQLite, the import adds a task to turn on SQLite's write-ahead log: `journal_mode=wal` in `DATABASE_URL`, such as `sqlite://database/database.sqlite?mode=rwc&journal_mode=wal`. It made creating records about three times faster in the benchmark. The setting is stored in the database file, so once the Rust application has opened the file, the PHP application that shares it uses the log too. Read [Many token requests on SQLite](sanctum.md#many-token-requests-on-sqlite) before you turn it on: it says what that means for backups, how to check it is on, and how to go back. The owner of the application decides. Leave it out until they do, or if they'd rather keep the file as it is. Register Restify in `src/app.rs`, so that the application has Restify's commands. The import later replaces this line with the providers it generates. ```rust Application::configure() .with_providers(|providers| { providers.add(restify::Restify::new()); }) ``` Then write the skills for AI coding agents, and the script that prints where these guides are, to `.agents/skills` and `.claude/skills`: ```bash cargo run -- restify:install ``` Where the build goes: the starter's `.cargo/config.toml` sends most of it to `~/.cargo/build/laravel-rust`, a cache that every Laravel application on the machine shares (the framework's `development.md`, "The shared build cache"). Clean one application with `cargo clean --workspace`. A plain `cargo clean` deletes the shared cache too. To keep the whole build in `target/`, delete the `build-dir` line. | Feature | Turn it on when | | --- | --- | | `sanctum` | The PHP routes use `auth:sanctum`. API clients keep their tokens ([Sanctum tokens](sanctum.md)). | | `import` | You run `restify:import`. Remove it after the migration. | | `testing` | Only in `[dev-dependencies]`: the replay of the recordings. | | `mcp`, `openapi` | On by default ([Installation](installation.md#choosing-features)). | ## Check what won't migrate ```bash cargo run -- restify:import ../php-app/restify-manifest.json --check ``` This prints what the PHP application uses that Restify for Rust doesn't serve the same way, each with the reason, and writes nothing. Read it before you go on: if a line is something the application can't live without, the migration isn't ready yet. | The PHP application uses | Why it doesn't migrate | | --- | --- | | `Base64File` fields, and a `File` or `Image` field without a nullable text column | `Field::file` takes a file sent in a form, and keeps its path in such a column ([Files and images](files.md)). | | `HasActionLogs` | Action logs aren't written. | | Sanctum's `statefulApi()` | Single-page apps that log in with the session cookie get `401`: only bearer tokens are read ([Sanctum tokens](sanctum.md)). | | A user model with a UUID or text key | Sanctum's `tokenable_id` is read as a number, so those users can't log in with a token. | | `MorphTo` in `related()` | It can't be shown with `?related=` yet. The model still declares it. | | `MorphedByMany` in `related()` | The import doesn't declare it. Restify serves it: declare it with `#[morphed_by_many]` and list it with `Related::many` ([Relationships](relationships.md)). | | Through relationships in `related()` | They can't be shown with `?related=` yet ([Relationships](relationships.md)). | | `canAttach`, `canDetach`, `canSync`, `attachCallback`, `detachCallback`, `$attachers`, `$detachers` | Only `authorize` decides an attach, a detach or a sync, and the relationship itself does it. | | Laravel Scout | `?search=` searches the database columns. | | The repository cache, the policy cache | Answers aren't cached, and policies are asked every time. | | `search.use_joins_for_belongs_to` or `sort.use_joins_for_belongs_to` | Not served. Search and sort by a related model's column with a scope ([Scopes](filtering.md#scopes)). | | A field class other than plain `field()`, such as a relation field in `fields()` | Only plain fields are translated. The others are written by hand. | | `hidden(fn ..)` on a field | It gets a stub gate that refuses. Nobody sees or sends the field until its task translates the closure. | | A global scope on a model, as the manifest's `global_scopes` lists them. A manifest from before that key existed doesn't list them, so the import guesses: a method that calls `addGlobalScope`, or a trait it doesn't know | The repository's `query()` stub keeps no rows until its task adds the same filter. | | `$id` other than `id` on a repository | Rust shows the model's primary key as each resource's `id`. | | `$with` on a repository | Rust shows a relationship only when the client asks for it with `?related=`. | | A `related()` entry built by a closure | Only relationships declared on the model are loaded. | | An order of `$match`, `$search` and `$sort` that no order of `fields()` keeps | `GET /filters` lists the fields in another order. A client that reads the list by name isn't affected. | | GraphQL | Only JSON:API and MCP are served. | | A `prefix` outside `api/` | A repository's prefix is served inside the `api` group only. | | Middleware in `restify.middleware` other than `api` and `auth:sanctum` | It gets a stub that answers `501` to every request until it is written again as framework middleware. Another `auth:` guard means a login is still needed: its inputs refuse guests. | | Password hashing other than bcrypt | Stored passwords wouldn't verify. | | Overridden repository methods Rust has no hook for | Each becomes a task that says what to do. | `MIGRATION.md` repeats the list, and adds the known differences every migration has, such as a `404` message that names the PHP model class. ## Record what PHP answers The recordings prove the migration: each one is a request PHP answered, with its answer. Record against a copy of a database with real data, such as a copy of production, never against production itself. Point the PHP application's `.env` at the copy while you record. If the application has no `.env`, make one first: ```bash cp .env.example .env php artisan key:generate ``` - SQLite: copy the file, such as `cp database/database.sqlite database/record.sqlite`, and set `DB_DATABASE` in `.env` to the copy's full path. Laravel 12 and 13 read the SQLite file from `DB_DATABASE`, unless `DB_URL` is set. - PostgreSQL or MySQL: restore a dump of the database into a new database, such as `php_db_record`, and set `DB_DATABASE` to its name. ```bash php artisan restify:record --generate --as=admin@example.com --as=member@example.com ``` Pass one `--as` user for each kind of user that sees different data. `--generate` writes these scenarios to `restify-oracle/scenarios`, and stops. It never overwrites a scenario file that is already there: it prints `kept` for that file. To generate one again, delete it first. - One per repository, with every step sent as each `--as` user. - `guest`: each list, and the first record of each public repository, sent without a token. - `auth`, when PHP serves `Route::restifyAuth()`: logins and registrations that fail, and one registration that succeeds. Its new token is marked `volatile`. Read them. Remove requests that would put private data in a file. Add the requests your clients really send, including writes and a successful login, which needs a real password. Then record: ```bash php artisan restify:record --scenarios=restify-oracle/scenarios --allow-writes ``` To record an upload, give the step's `request` a `files` key, such as `"files": {"avatar": {"path": "../files/photo.png", "name": "photo.png", "type": "image/png"}}`. The path starts from the scenario's folder, so keep the files next to `restify-oracle/scenarios`, in `restify-oracle/files`: the Rust test reads them from there. A stored file gets a random name each time, so list where the response shows it in `hashed`, such as `"hashed": ["/data/attributes/avatar"]`. The name is then compared as `{hash}`. Each scenario runs in a database transaction that is rolled back, so the database is the same afterwards. Uploads go to the disk the field names, and a rollback doesn't remove them: record against a disk you can empty afterwards. Debug mode is off while recording, whatever `APP_DEBUG` says: a debug error page holds a stack trace that no other application can answer. Tokens aren't written to the recordings: a header holds `{{token:admin@example.com}}`, and the Rust test makes a token for that user when it replays. `--as` also applies to a scenario file that sets no `authorization` header. The cassettes are in `restify-oracle/cassettes`. A scenario file, key by key: | Key | What it is | | --- | --- | | `scenario` | The name. The cassette is `.json`. | | `now` | The time the clock is frozen at while recording and replaying, such as `2026-01-15T10:00:00Z`. | | `headers` | Headers sent with every step, such as `"accept": "application/json"`. | | `headers.authorization` | `"Bearer {{token:}}"` sends the steps as that user. `null` sends them as a guest. | | `steps[].id` | The step's name, unique in the scenario. | | `steps[].request` | `method`, `path` with its query, and optional `headers` and `body`. A step's `headers` override the scenario's, and `null` removes one. | | `steps[].request.files` | Uploads, by field: the file's `path` from the scenario's folder, its `name` and its `type`. | | `steps[].hashed` | JSON pointers to stored file names, which are random. The replay compares them as `{hash}`. | | `steps[].volatile` | JSON pointers to values that change on every run, such as `["/meta/token"]`. The replay checks that each has the same type, not the same value. | | `config` | Settings changed in PHP while recording, such as `{"restify.auth.frontend_app_url": "http://localhost"}`. The cassette keeps them. Set the Rust test up the same way. | | `{{mail:}}` in a `path` or `body` | The link that an earlier step emailed, such as a password reset link: its path and query. `{{mail::token}}` is one value from its query. The cassette records each emailed link in the answer's `mail`. | Any method but `GET` needs `--allow-writes`. The package's `docs/recording.md` has the details: https://github.com/BinarCode/laravel-restify-rust/blob/main/php/docs/recording.md. ## Import Copy the recordings first: the import writes one parity test for each cassette it finds. ```bash cp -r ../php-app/restify-oracle . cargo run -- restify:import ../php-app/restify-manifest.json ``` | Option | What it does | | --- | --- | | `--check` | List what won't migrate, and write nothing. | | `--migrations` | Also write a migration for each table. Use it only when the tests start from an empty database, not from a copy of PHP's. | | `--force` | Overwrite the files that differ from what the import writes: your changes, or an older import's output. | | `--path` | The Rust application's folder, when you don't run the command inside it. | The import also registers Restify in the application: `pub mod restify_provider;` in `src/lib.rs`, and Restify's providers in `src/app.rs`, in `.with_providers(..)` after `Application::configure()`, in place of `providers.add(restify::Restify::new());`. If one of those files isn't laid out as `laravel new` leaves it, the import stops before writing anything and says what to add by hand. It replaces two files of the starter application: `src/models/user.rs` and `src/models/mod.rs`. The new `User` model comes from PHP's `users` table, and keeps `UserFactory`, which the starter seeder calls. A file counts as the starter's while its first line doesn't say that `restify:import` generated it. With `--migrations`, the starter's `users` migration stays, and a new migration adds the columns PHP has and it lacks. It decides about every file before it writes any. If a file is already there and differs from what it would write, it writes nothing at all, names the files and exits with `1`. A file differs when you changed it, and also when the manifest changed since the last import. To import again, for example after the PHP application changed: commit your work, run the import with `--force`, then bring your changes back from `git diff`. For the same manifest it writes the same files. It also stops before writing anything when the manifest has a name that can't become a Rust name: one with no ASCII letter or digit, or two names that give the same one, such as two models called `Post` in different namespaces, or the columns `first-name` and `first_name`. The error lists each one. Rename it in the PHP application, then export again. If a write fails halfway, for example because a folder can't be written to, the import puts back every file it already changed, so the application is as it was. The manifest is treated as data. Every name from it is made safe for where it goes: a Rust name, a comment, a text in quotes, a file name, or Markdown. In `MIGRATION.md`, PHP code sits in fenced blocks and names in backticks. Neither is an instruction to the agent that does the tasks. Its output compiles as it is, before any task is done. ## Testing against a copy of the database The recordings were made against real rows, so the Rust tests must start from the same rows. Put a dump of the PHP database, with its rows, in the folder of the recordings: ``` restify-oracle/database/schema/-schema.sql ``` The generated test, `tests/restify_parity.rs`, reads its database dumps from `restify-oracle` when that folder has a `database/schema` folder. Each test then gets a fresh database built from the dump, and what the test writes is rolled back, as PHP rolled back each scenario. The dump stays out of the application's own `database/schema`, which is built into the binary, so your data never ships in the release binary. Dump the database you recorded on, the copy, not PHP's real one. Run these in the Rust application's folder, `my-api`, next to the PHP application's folder, `php-app`. First make the folder for the dump: ```bash mkdir -p restify-oracle/database/schema ``` Then make the dump, and run the tests: | Database | Make the dump | Run the tests with | | --- | --- | --- | | SQLite | `sqlite3 ../php-app/database/record.sqlite .dump > restify-oracle/database/schema/sqlite-schema.sql` | `DB_CONNECTION=sqlite DATABASE_URL=sqlite::memory: cargo test --test restify_parity` | | PostgreSQL | `pg_dump --no-owner --no-privileges php_db_record > restify-oracle/database/schema/postgres-schema.sql` | `DB_CONNECTION=postgres DATABASE_URL=postgres://user:pass@127.0.0.1/parity cargo test --test restify_parity` | | MySQL | `mysqldump --routines --no-tablespaces php_db_record > restify-oracle/database/schema/mysql-schema.sql` | `DB_CONNECTION=mysql DATABASE_URL=mysql://user:pass@127.0.0.1/parity cargo test --test restify_parity` | - Point the tests at a new, empty database, such as `parity`, never at the PHP database itself. Laravel for Rust creates numbered copies of it, such as `parity_1`, and rebuilds them from the dump. - PostgreSQL and MySQL need the `psql` or `mysql` client on the `PATH` to load the dump. In-memory SQLite loads it without a client. - The dump holds PHP's `migrations` table. A Rust migration with a name already in it is skipped, such as `laravel new`'s `0001_01_01_000000_create_users_table`, which has the same name as Laravel 11's. Delete any other starter migration whose tables the dump already has, or the test database can't be built. - Make the dump again whenever you record again, so the rows match the recordings. What has been proven, and how: - The import's own check replays recordings made from seeded data, on SQLite and on PostgreSQL. - Recordings made by `restify:record` with a token replay against a `sqlite3 .dump` of the database they were recorded on, on in-memory SQLite. Without the dump, the same tests fail with "no such table". This was checked by hand on Restify's test application. It isn't part of Restify's test suite yet. What hasn't been proven: loading a PostgreSQL or a MySQL dump with `psql` or `mysql`, and a dump that holds something the framework's loader doesn't expect, such as a PostgreSQL extension. If the test database can't be built, the error names the dump. ## Working through the tasks ```bash cargo build cargo test --test restify_parity ``` Each task in `MIGRATION.md` has a number, the PHP code to read, the Rust code to change, what to do, and the guide to read. The code has a `// TODO(restify-import #n)` marker at the same place. Until a task is done its code stays closed: - A stubbed policy method or gate refuses. So does the gate of a field PHP hides with a closure. - A stubbed action, getter or middleware answers `501`. This includes app-wide middleware from `restify.middleware`, and a login guard other than Sanctum. - A stubbed filter keeps no rows. A stubbed sort keeps the order. - A stubbed `query()` keeps no rows: for `mainQuery`, `indexQuery` and `showQuery`, and for a model's global scope. - A validation rule the import can't translate refuses the field (`prohibited`) until its task writes it. This also applies to an advanced filter's rule object, and to an action's nested keys, such as `items.*.id`. The import translates every rule the framework has a rule for that checks the same. It leaves closed the rules that compare a field with a value, such as `required_if:role,admin`: PHP compares loosely, so `1` matches `true`, and the framework compares exactly, so Rust would let through what PHP refuses. In an advanced filter, `date` becomes `Rule::date()`, which takes a date as `2026-01-31` only. PHP also takes other forms, such as `2026-01-31 10:00`. - A field list the export couldn't read, such as a `fieldsForStore` that threw, shows and writes no field. So an unfinished migration answers `403` or `501` where PHP answered, never with data PHP would have hidden. Do the tasks one group of `MIGRATION.md`'s "Tasks by kind" at a time. If there is a task for the `viewRestify` gate, do it first: until it is done, no cassette can pass. Then do the groups in this order: policy methods, gates, field values, validation rules, write hooks, queries, actions and getters, then the rest (setup, column types, relationships, other). After each group, run the parity test. The number of cassettes that replay should go up, and never down. Delete each marker when its task is done: `grep -rn "TODO(restify-import" src` lists what is left. ## Reading a replay failure A cassette that doesn't replay prints the step's name, then what PHP answered and what Rust answered: ``` --- PHP: { "status": 200, "headers": { .. }, "body": { "data": [ .. ] } } --- Rust: { "status": 403, "headers": { .. }, "body": { "message": "Unauthorized to view repository posts. Check \"allowRestify\" policy." } } ``` Find the first difference, then: | Rust answers | Usually | | --- | --- | | `403` where PHP answered `200` | A policy method or a gate is still a stub. | | `501` | An action, a getter or a middleware is still a stub. | | An attribute too many or missing | A field's visibility, `can_see`, or a computed value. | | Other rows, or another order | A scope, a filter, a sort, or `Repository::query`. | | `422` with another message | A validation rule. | | Another value in one attribute | A cast, a computed value, or the number of decimals. | Change the Rust code until the answers match. Never edit a cassette. ## When PHP answers wrongly Sometimes the recording shows a PHP bug, such as a `500`. Don't copy the bug, and don't fix it on your own: ask the owner. If the owner agrees that Rust may answer differently, add the step to `restify-oracle/divergences.json`, with the JSON pointer of what differs and the reason: ```json [ { "id": "php-500-on-empty-search", "scenario": "posts-index", "step": "search-with-no-term", "pointer": "/status", "reason": "PHP answers 500 when ?search= is empty. The owner chose a 200 with every post." } ] ``` The replay then ignores that difference, and fails if it ever goes away, so the list never holds a stale line. `divergences.json` is the one place for every difference you accept: - a PHP bug the owner accepted; - a row of [Where Restify for Rust doesn't copy PHP](#where-restify-for-rust-doesnt-copy-php), below; - a line of `MIGRATION.md`'s "Known differences", or of the `--check` list. The only exception is a difference that one database shows and another doesn't: see [A difference on one database only](#a-difference-on-one-database-only). ### What a pointer covers The replay compares one document per step: `{"status", "headers", "body", "mail"}`. A pointer covers everything under it: `/body/data` covers the whole list, and `/body` the whole body. It covers nothing beside it: `/body` doesn't cover `/status`. So a step whose status and body both differ needs two entries, one with `/status` and one with `/body`. ### Where Restify for Rust doesn't copy PHP Restify for Rust answers these cases differently from PHP on purpose. Most are PHP bugs that Rust fixes instead of copying. Add each one your recordings show to `divergences.json`, with the reason. | Request | PHP answers | Rust answers | | --- | --- | --- | | `POST /api/logout` with a valid token | `500` `Server Error`, after deleting the token | `200` `{"message": "Successfully logged out."}`, after deleting the token | | A path naming no repository, such as `GET /api/restify/widgets` | `500` `Server Error` | `404` `{"message": "Repository widgets not found."}` | | `?filters=` that isn't a base64-encoded JSON list | `500` `Server Error` | `422`, a validation error of `filters` that says what to send | | `apply-restify-advanced-filters` with a `filters` body that isn't a list | `500` `Server Error` | `422`, a validation error of `filters` | | `apply-restify-advanced-filters` with `?filters=` and no `filters` in the body | `500` `Server Error` | The list filtered by `?filters=`, as on `GET` | | `GET /api/restify/search` when a globally searchable repository has its own prefix | `403` for the whole search | The results, with each `link` under the repository's own prefix | | A bulk create or update item that breaks any rule its field has its own message for, such as `required` or `in` | The rule's default message, such as "The 1.title field is required." or "The selected 0.status is invalid.": PHP looks the messages up under a wrong key (`*title.required`), so it never finds them | The field's own message, such as "A post needs a title.", as on the single endpoints | | A list with `?related=` naming a relationship whose model the user may not see | `403` "You are not authorized to see the [App\Models\Task] relationship from the BelongsTo field from the BelongsTo field. Check the [show] method from the [App\Policies\TaskPolicy]" | `403` "You are not authorized to see the task relationship: the tasks repository refuses to show it. Check what its `authorize` answers for `Action::Show`.": Rust has no PHP class or policy to name | | A field with `required` and `string`, sent as `""` | `422` with two messages, "The title field is required." and "The title field must be a string.": Laravel's `ConvertEmptyStringsToNull` middleware turns `""` into `null` before the rules run, and `null` isn't a string | `422` with "The title field is required." only | | An attach to a relationship declared with `withTimestamps()` | `201` with each pivot row's `created_at` and `updated_at` as a raw PHP `DateTime` object, such as `{"date": "2026-12-03 22:17:24.001726", "timezone_type": 3, "timezone": "UTC"}`: Restify for PHP fills them with `new DateTime`, which nothing turns into a date string | `201` with the pivot rows, without `created_at` and `updated_at` | | An attach of a model that is already attached, such as `POST /api/restify/teams/1/attach/users` with `{"users": [3]}` when user 3 is a member | `500` with the database's error when the join table has a unique index on its two keys; `201` and a second join row when it hasn't: Eloquent's `attach()` inserts without checking | `422` that names the ids under the relationship's name, such as "User 3 is already attached to this Team. Leave it out, or detach it first.", and nothing is written. The same for one id sent twice in one attach | | MCP `resources/list` | One resource, `file://instructions/application-info.md`, a text about the application and its versions | An empty list. `initialize` announces resources in both | | A match on a column that `$match` lists with the type `date`, such as `?due_date=2026-10-12` for `'due_date' => 'date'` | `200` with every row: PHP's `MatchFilter` knows the type `datetime`, not `date`, so it adds no condition | `200` with the rows of that day | | `?related=` or `include` deeper than 3 relationships, such as `?include=tasks.comments.task.project`, or naming more than 20 | `200` with the related rows: PHP has no limit | `422` that names the limit ([How deep, and how many](relationships.md#how-deep-and-how-many)). This is a safety limit, not a PHP bug. List the step with `/status` and with `/body`. Raising `RESTIFY_RELATED_MAX_DEPTH` or `RESTIFY_RELATED_MAX_PATHS`, or setting one to `0`, matches PHP but lets one request load the same rows again at every level | ## A difference on one database only Some answers depend on the database, such as where `NULL` sorts. `divergences.json` applies on every database, and each difference it lists must differ, so it can't hold one that only PostgreSQL shows. List that one in the test instead. Write the cassette's test in `tests/restify_parity.rs` as a function that picks its list, with the step, the JSON pointer and the reason of each entry: ```rust #[laravel::test(app = app)] async fn index_sort(app: Application) -> laravel::Result<()> { let postgres = std::env::var("TEST_DATABASE_URL").is_ok_and(|url| url.starts_with("postgres")); let except: &[(&str, &str, &str)] = if postgres { &[ ("nullable-column", "/body/data", "PostgreSQL sorts NULL last when ascending; SQLite first."), ("nullable-column-descending", "/body/data", "PostgreSQL sorts NULL first when descending; SQLite last."), ] } else { &[] }; replay_cassette(&app, "index-sort", except).await } ``` Like `divergences.json`, each difference listed must still differ: when one goes away, the test fails until you remove it. `cassette!` and `mcp_cassette!` take the same list, but a difference that every database shows belongs in `divergences.json`. Never use either list to hide a task that isn't done. ## What the import writes From the manifest, the import writes: - A model for each Eloquent model: its columns with their types and casts, its relationships, including polymorphic ones with their `#[morph]` enum, and soft deletes. - `UserFactory` for the user model, which `laravel new`'s seeder calls. - A repository for each Restify repository: its fields and their visibility, search, match, sort, group-by, advanced filters with their rules, relationships with their pivot fields, nested routes, `PER_PAGE`, `prefix()`, `PUBLIC`, its own middleware, global search, and the MCP tools of `HasMcpTools`, with `fields_for` when `fieldsForMcpIndex` or `fieldsForMcpShow` lists other fields. - The fields in an order that keeps PHP's order of `$match`, `$search` and `$sort`, because `GET /filters` lists them in the order of `fields()`. When no order keeps all three, `--check` says so. - An input for each repository, with the validation rules it can translate. A password arrives as a `String`, which the model's `PasswordHash` column hashes. A password column is never a response field. - A `date` column, as a `Date` on every database. Clients write, filter and sort by it. When the model casts it to a date, the field shows it as PHP does, at midnight: `2026-01-02T00:00:00.000000Z`. A password input is a `Password`. Laravel's `boolean` rule on an advanced filter becomes `Rule::custom(php::Boolean)` ([Filtering](filtering.md#advanced-filters)). - A policy for each PHP policy, with one method per PHP method, including attach, detach and sync. A method whose PHP body only returns `true` or `false` gets that answer, with a comment that names the PHP source. Every other method is a task. A PHP method that also takes the related model, such as `attachUsers(User $user, Team $team, User $member)`, gets it too: `authorize` passes the model being attached, or all of them for a sync. - Actions and getters, each as a stub with its task. PHP offers an action on the list and on each record unless it says otherwise. The import then writes `Custom::index_and_show`, which does the same. - Nothing for a method that changes nothing: one that only returns its query, such as the `indexQuery`, `showQuery` and `mainQuery` that `restify:repository` writes, or one that only calls its parent's method. - `src/restify_provider.rs`, with Sanctum when the routes use it. When PHP's settings are stricter than Restify for Rust's defaults, it also writes `php_settings()`, registered after `restify()`. It sets the MCP server's mode, makes the MCP server read-only, and sets Sanctum's token lifetime (`sanctum.expiration`) to PHP's values. Each one applies unless its variable is set in the environment (`RESTIFY_MCP_MODE`, `RESTIFY_MCP_READ_ONLY`, `SANCTUM_EXPIRATION`). A repository whose `mcpAllowsIndex` returns `false` gets `.index(false)` on its `McpTools`. When PHP's `restify.middleware` has `AuthorizeRestify`, it also writes `view_restify`, the `viewRestify` gate as a middleware. PHP lets every request through in the `local` environment and asks the gate everywhere else, and so does `view_restify`. If PHP's gate is the package's default, which lets nobody in, `view_restify` refuses everyone too. If the PHP application wrote its own gate, `view_restify` refuses everyone until its task is done. - The MCP server, at the path of PHP's `Mcp::web(..)` server, or `.without_mcp()` when PHP serves none. Rust serves one MCP server: `--check` lists each other one. This needs Restify's `mcp` feature, which is on by default. If `Cargo.toml` turns it off, a task says to turn it on and import again. - File and image fields as `Field::file` and `Field::image`, with the disk, folder, name, name and size columns, `prunable` and `deletable` of PHP's field, and an `UploadedFile` in the input structs with the field's file rules. A closure that names or stores the file, and a temporary URL, become tasks ([Files and images](files.md)). - `tests/restify_parity.rs`, with one test per recording. A recording of MCP requests gets one `mcp_cassette!` test for each PHP server it called. When the application has file fields, each test puts their disks in temporary folders first, so a replay never writes to the application's storage. - With `--migrations`, a migration for each table, or for the columns PHP has that a starter migration lacks. It leaves as a task anything that is code in PHP: policy and gate bodies, closures, custom filters, sorts and searches, computed values, hooks, actions, getters, middleware, and rules it can't translate. The fixture application of Restify's own tests gives 60 tasks for 10 repositories: about 6 per repository. ## Cutting over Switch production to the Rust application when all of these hold: - `cargo test` passes, and every recording replays. Each difference left is in `divergences.json` with its reason, or, if only one database shows it, in that cassette's test. - No `TODO(restify-import` marker is left. - The owner has read the `--check` list again and accepted each line. - The Rust application reads the same database as PHP: its `.env` now names PHP's real database, not the copy you recorded on. It runs no migration that changes PHP's tables. Without `--migrations`, the import writes none. - A token made by PHP works with Rust ([Sanctum tokens](sanctum.md)). - Both applications save files on the same disk, such as the same S3 bucket or the same `storage/app/public` folder, so each finds the files the other saved. A path in the database is only a path: the file must be there too. Point the Rust application's disk at PHP's before the switch, and check that a file uploaded through PHP shows in Rust. - The release binary was built without the dump: it lives in `restify-oracle/`, not in `database/schema`. - The PHP application can still be deployed, so you can switch back. - Every host your clients use is trusted. See the next section. - You went through [Before you go to production](production.md). - The Rust application has PHP's `APP_KEY`, and sends email. Links that PHP emailed before the switch keep working: reset links, because the tokens stay in `password_reset_tokens`, and verification links, because Rust checks their signature with the same key. See [Authentication](authentication.md#forgot-and-reset-password). ### Trust every host your clients use In production, Laravel for Rust answers `400` with `Bad request.` when a request's `Host` header is neither the host of `APP_URL` nor one of its subdomains. Laravel for PHP 11 and later checks no host unless the application calls `trustHosts()`. So a request that PHP served can fail after the switch, such as one from: - a second domain, such as `api.example.org` when `APP_URL` is `https://example.com`; - a load balancer's health check that calls the server by its IP address; - a proxy that sends its own host, such as `localhost:8080`, instead of the client's. Before the switch, set `APP_URL` to the address clients use. List any other host in `src/app.rs`. Include the `APP_URL` host too, because the list replaces it: ```rust .with_middleware(|middleware, _| { middleware.trust_hosts(["example.com", "*.example.com", "example.org"]); }) ``` The `local` and `testing` environments check no host, so tests and a laptop never show the problem. Before the switch, send one request with each real host to the Rust application running with `APP_ENV=production`. See [Trusting hosts](https://github.com/laravel/rust-framework/blob/0.x/docs/middleware.md#trusting-hosts) in the framework's guide. Then remove the `import` feature from `Cargo.toml`.