Restify for Laravel for Rust

Docs / Start here

Repositories

everything a repository can declare.

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.

pub struct UserRepository;

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

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

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

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

Where a repository lives #

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

What a repository declares #

Everything but the three types has a default.

ItemDoesDefaultGuide
type ModelThe model the repository servesRequired
type StoreThe input that creates a modelRequiredWriting
type UpdateThe input that updates a modelRequiredWriting
fn fieldsThe attributes a resource shows, and the columns clients may search, filter and sort byNone, so a resource shows nothingFields
fn fields_forThe attributes of one view, when they differ from fieldsfields()Fields
fn uri_keyThe name in URLs and tool namesThe table, in kebab-caseBelow
fn resource_typeThe type of a resourceThe tableBelow
fn scopesFilters and sorts with their own queriesNoneFiltering
const PER_PAGEThe page size when a request doesn't say15Filtering
fn queryNarrows every query the repository runsThe whole tableBelow
fn relatedThe relationships clients may load with ?related=NoneRelationships
fn creating, fn updatingFinish a write before it runsNothingWriting
fn stored, fn updated, fn deletedRun after a writeNothingWriting
fn authorizeWho may do whatRefuses everythingAuthorization
fn actionsOperations that may write, such as publishing a postNoneActions and getters
fn gettersOperations that only read, such as counting postsNoneActions and getters
const MAX_BULKThe most items one bulk request may hold100Bulk operations
const RELATABLE_PER_PAGEHow many models of this repository a related list loads for each record15Relationships
fn soft_deletesThe column of a soft-deleting modelNoneSoft deletes
fn prefixA path to serve the repository under instead of the provider's prefixNoneBelow
fn middlewareMiddleware for this repository's endpoints onlyNoneBelow
const PUBLICServes the list, the show and the getters to guestsfalseBelow
const MCPWhich operations AI agents may runNone, so no toolsMCP

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:

/// 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:

use laravel::db::Builder;

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

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

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

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

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

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

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

A model that query leaves out answers 404 to show, update and delete, the same as a model that doesn't exist. Rows reached from another repository are narrowed too: a Related::through relationship that shows DraftRepository shows only the drafts its query keeps, and an attach, detach or sync finds only those rows (see Who can see a relationship). 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:

{
    "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 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:

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:

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, 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:

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 throughIts middleware run
Its own routes, such as GET /api/restify/labelsYes, around the endpoint
Its MCP tools, in direct mode and through execute-operationYes, before the tool
A nested route of another repository, such as /api/restify/posts/1/comments for the comments repositoryYes, 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 repositoryYes, before the operation
?related= (or include) on another repositoryNo
The global search, /api/restify/search and the global-search toolYes, before the repository is searched. A refusal refuses the whole search, as in Restify for PHP

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

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

Configuration #

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

VariableDoesDefault
RESTIFY_MAX_PER_PAGEThe largest page a request may ask forNo limit
RESTIFY_SERIALIZE_SHOW_METAWhether a shown record carries meta; see Authorizationtrue
RESTIFY_SERIALIZE_INDEX_METAWhether a listed record carries metafalse
RESTIFY_TOKEN_TTLHow many minutes a login token lasts; see AuthenticationNever expires
FRONTEND_APP_URLYour frontend's address, which reset and verification links point to; see Authentication, which also lists RESTIFY_PASSWORD_RESET_URL, RESTIFY_USER_VERIFY_URL, RESTIFY_PASSWORD_RESET_TIMEBOX and RESTIFY_REVOKE_TOKENS_ON_RESETNone
RESTIFY_MCP_MODEHow the MCP server lists its tools: wrapper or direct; see MCPwrapper
RESTIFY_MCP_READ_ONLYWhether the MCP server refuses every tool that writes; see MCPfalse

RestifyConfig also has the settings of forgot password, reset password and email verification, such as FRONTEND_APP_URL: see Authentication. Its search_case_sensitive is PHP's setting of the same name: see Search.

Moving a PHP config/restify.php #

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

PHP keyHere
baseRestify::new().prefix("/restify"), inside the api group; see Installation
middlewareRestify::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
pagination.max_per_pageRESTIFY_MAX_PER_PAGE
repositories.serialize_index_meta, serialize_show_metaRESTIFY_SERIALIZE_INDEX_META, RESTIFY_SERIALIZE_SHOW_META
repositories.apply_main_query_to_actions_and_getters, apply_main_query_to_writesNot 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_ttlRESTIFY_TOKEN_TTL
auth.user_model, auth.table, auth.providerThe user type you give Restify::auth::<R>() and Sanctum<User>
auth.frontend_app_url, password_reset_url, user_verify_url, password_reset_timebox, revoke_tokens_on_resetFRONTEND_APP_URL, RESTIFY_PASSWORD_RESET_URL, RESTIFY_USER_VERIFY_URL, RESTIFY_PASSWORD_RESET_TIMEBOX, RESTIFY_REVOKE_TOKENS_ON_RESET; see Authentication
search.case_sensitivesearch_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_toNot settings. To search or sort by a related model's column, write a Scope::searching or Scope::sorting; see 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_onlyRESTIFY_MCP_MODE, RESTIFY_MCP_READ_ONLY
mcp.* (the others)The provider's MCP methods; see MCP

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.