Restify for Laravel for Rust

Docs / Building

Files and images

file uploads, where they are saved, how they are shown, and deleting them.

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<String> in the model.

#[model]
pub struct Document {
    pub id: i64,
    pub title: String,
    pub attachment: Option<String>,
    pub attachment_name: Option<String>,
    pub attachment_size: Option<i64>,
    pub cover: Option<String>,
    // ..
}

The input struct gets a field with the column's name, of type Sometimes<UploadedFile>. 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(..)]:

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<UploadedFile>,
    /// An image of at most 1 KB.
    #[fill(skip)]
    #[validate(image, max_kilobytes(1))]
    pub cover: Sometimes<UploadedFile>,
}

Then list the field in the repository. Field::file shows the path; Field::image shows the image's URL:

fn fields() -> Vec<Field<Document>> {
    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 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 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:

curl -X POST https://example.com/api/restify/documents \
  -H "Authorization: Bearer $TOKEN" -H "Accept: application/json" \
  -F title=Report -F attachment=@report.pdf
RequestWith files
POST /api/restify/documentsCreates the model and saves the files.
PUT /api/restify/documents/1Updates the model and saves the files.
POST /api/restify/documents/1The same as PUT. Browsers' forms can only send POST, so this is the usual way.
PATCH /api/restify/documents/1Changes 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.

MethodWhat it changesExample
.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<String>. 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<i64>.

Neither column should be in the input struct: clients can't write them, only the upload can.

Showing the file #

FieldShows
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.

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 happensWithout prunable()With prunable()
A new upload replaces the fileThe old file stays on the disk.The old file is deleted.
DELETE /api/restify/documents/1The files stay.The files are deleted after the record is.
DELETE /api/restify/documents/bulk/deleteThe 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:

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:

async fn creating(
    create: CreateBuilder<Document>,
    input: &NewDocument,
    _request: &Request,
) -> laravel::Result<CreateBuilder<Document>> {
    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:

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:

.form(json!({ "milestone_id": milestone.id.to_string(), "title": "Design", "estimate": "2" }))

The example app's 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 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.