# 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<String>,
    #[validate(min_value(0))]
    pub votes: Sometimes<i64>,
    /// Whether the post is featured. Only an admin may set it: see the field's `can_store`.
    pub featured: Sometimes<bool>,
    /// Readers' average rating, from 0 to 10.
    #[validate(between(0, 10), invalid = "The :attribute field must be a number.")]
    pub rating: Option<Decimal>,
    /// 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<EloquentTimestamp>,
}
```

- `#[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<String>,
    /// The post's text. Send `null` to clear it.
    pub body: Sometimes<Option<String>>,
    #[validate(min_value(0))]
    pub votes: Sometimes<i64>,
    // `featured`, `rating` and `published_at` as in `NewPost`, each in a `Sometimes`.
}
```

Declare every field of an update as `Sometimes<T>`. A field the request leaves out then keeps its value. With `Sometimes<Option<T>>`, 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::<M>(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<String>,
}

impl ValidatesRequest for EditMilestone {
    async fn authorize(request: &Request) -> laravel::Result<bool> {
        request.authenticated().await
    }

    async fn rules(&self, request: &Request, rules: Rules) -> laravel::Result<Rules> {
        let changed = restify::updating::<Milestone>(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<T>` | The type or `null`, and not required |
| `Sometimes<T>` 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<Post>,
    _input: &NewPost,
    request: &Request,
) -> laravel::Result<CreateBuilder<Post>> {
    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<bool>`, 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<Post>,
    input: &NewPost,
    request: &Request,
) -> laravel::Result<CreateBuilder<Post>> {
    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<UpdateBuilder<'a, Post>> {
    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"] })
    }
}
```
