# 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 <manifest> --check` |
| 4. Record what PHP answers | PHP | `php artisan restify:record` |
| 5. Generate the Rust code and its tasks | Rust | `restify:import <manifest>` |
| 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 `<name>.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:<id or email>}}"` 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:<step id>}}` in a `path` or `body` | The link that an earlier step emailed, such as a password reset link: its path and query. `{{mail:<step id>: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/<connection>-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`.
