# Routing

- [Basic routing](#basic-routing)
    - [The default route files](#the-default-route-files)
    - [Available router methods](#available-router-methods)
    - [Redirect routes](#redirect-routes)
    - [View and Inertia routes](#view-and-inertia-routes)
    - [Listing your routes](#listing-your-routes)
- [Route parameters](#route-parameters)
    - [Optional parameters](#optional-parameters)
    - [Restricting parameter values](#restricting-parameter-values)
    - [Models in route parameters](#records-in-route-parameters)
- [Linking to routes](#routes-are-identified-by-their-handlers)
- [Route groups](#route-groups)
    - [Prefixes](#prefixes)
    - [Middleware](#middleware)
    - [Domain routing](#domain-routing)
    - [Head metadata](#head-metadata)
- [Resource routes](#resource-routes)
    - [Register only some actions](#partial-resources)
    - [Nest a resource in its parent's module](#nested-resources)
    - [Mark a resource as single](#single-resources)
    - [Add middleware to some actions](#resource-middleware)
- [Fallback routes](#fallback-routes)
- [Form method spoofing](#form-method-spoofing)
- [Accessing the current route](#accessing-the-current-route)
- [CORS](#cors)
- [The health route](#the-health-route)

<a name="basic-routing"></a>

## Basic routing


ユーザーがページを開いたりフォームを送信したりすると、Laravelは`GET /greeting`のようにリクエストのメソッドとURIを調べ、一致するルートを探します。どのコードがリクエストを処理するかはルートが決めます。最も単純なルートは、URIとレスポンスを返すクロージャーを組み合わせたものです。

```rust
use laravel::prelude::*;

pub fn routes(route: &mut Router) {
    route.get("/greeting", async || "Hello World");
}
```


クロージャーが必要とする値を引数に指定すれば、リクエスト時にLaravelが値を渡します。たとえば`User`を受け取るクロージャーにはURIのIDに一致するユーザーが渡されるため、`/users/1`へのリクエストはユーザー1の名前を返します。そのIDを持つユーザーがいなければ、Laravelは`404`ページを返します。

```rust
use crate::models::User;

pub fn routes(route: &mut Router) {
    route.get("/users/{user}", async |user: User| user.name);
}
```


簡単なページにはクロージャーが便利ですが、アプリケーションが大きくなるとすべてのページのロジックがルートファイルに集まり、読みづらくなります。そこで、多くのルートでは`src/http/handlers`配下の専用モジュールに定義した非同期関数、すなわち[handler](/ja/rust/docs/handlers)を指定します。ルートファイルには短いURI一覧だけが残り、各ハンドラーには1ページ分のコードが収まります。ハンドラーの引数は[request](/ja/rust/docs/requests)、[service](/ja/rust/docs/container)、[route parameters](#route-parameters)などのエクストラクターで、戻り値は[response](/ja/rust/docs/responses)です。

```rust
use crate::http::handlers::users;

pub fn routes(route: &mut Router) {
    route.get("/users", users::index);
    route.get("/users/{user}", users::show);
    route.post("/users", users::store);
}
```

<a name="the-default-route-files"></a>

### The default route files


ルートファイルは`Router`を受け取る関数です。アプリケーションはルートファイルを`src/routes`に置き、`src/app.rs`で登録します。

```rust
Application::configure()
    .with_routing(|routing, _| {
        routing
            .web(routes::web::routes)
            .api(routes::api::routes);
    })
```


多くのアプリケーションでは、まず`src/routes/web.rs`でルートを定義します。`web`で登録したルートは`web` [middleware group](/ja/rust/docs/middleware#middleware-groups)内で実行され、セッション、暗号化されたCookie、[CSRF protection](/ja/rust/docs/csrf)を利用できます。


ほかのアプリケーション、スクリプト、サービスが呼び出すAPIのルートは`src/routes/api.rs`で定義してください。`api`で登録したルートはステートレスで、`api`ミドルウェアグループ内で実行されます。Laravelは`src/routes/api.rs`内のすべてのURIに`/api`を付けるため、そこで定義した`/users`ルートは`/api/users`に応答します。プレフィックスは`api_prefix`で変更できます。

```rust
routing.api(routes::api::routes).api_prefix("/api/v1");
```


どちらのグループも実行しないルートファイルを登録するには、`routes`を使います。セッション、CSRFチェック、プレフィックスは適用されないため、ミドルウェアを自分で選択します。

```rust
// src/app.rs
.with_routing(|routing, _| {
    routing
        .web(routes::web::routes)
        .api(routes::api::routes)
        .routes(routes::webhooks::routes);
})
```

```rust
// src/routes/webhooks.rs
use laravel::prelude::*;

use crate::http::handlers::webhooks;
use crate::http::middleware::verify_stripe_signature;

pub fn routes(route: &mut Router) {
    route.middleware(verify_stripe_signature).group(|route| {
        route.post("/webhooks/stripe", webhooks::stripe);
    });
}
```


`web`、`api`、`routes`を複数回呼び出すと、ルートを複数のファイルに分割できます。


クロージャーの第2引数はアプリケーションの設定なので、特定の環境でのみ一部のルートを登録できます。

```rust
.with_routing(|routing, config| {
    routing.web(routes::web::routes);

    if config.app.debug {
        routing.web(routes::debug::routes);
    }
})
```

<a name="available-router-methods"></a>

### Available router methods


ルーターには各HTTPメソッドに対応するメソッドがあります。

```rust
route.get(uri, handler);
route.post(uri, handler);
route.put(uri, handler);
route.patch(uri, handler);
route.delete(uri, handler);
route.options(uri, handler);
```


`GET`ルートは`HEAD`にも応答します。複数のメソッドに応答するには`on`を、すべてのメソッドに応答するには`any`を使います。

```rust
use laravel::http::Method;

route.on(&[Method::GET, Method::POST], "/search", search::show);
route.any("/webhooks/stripe", webhooks::stripe);
```

<a name="redirect-routes"></a>

### Redirect routes


別のURIにリダイレクトするだけのルートにはハンドラーが不要です。`302`には`redirect`を、`301`には`permanent_redirect`を使います。

```rust
route.redirect("/here", "/there");
route.permanent_redirect("/here", "/there");
```


リダイレクトはサイトの一部を改名するときに特に便利です。たとえばブログ記事を`/posts`から`/articles`に移した場合、訪問者や検索エンジンは以前のリンクを持っているため、新しいリンクにリダイレクトします。転送先では元のURIと同じパラメーターを使用できます。

```rust
route.permanent_redirect("/posts/{post}", "/articles/{post}");
route.permanent_redirect("/blog/{*slug}", "https://blog.example.com/{*slug}");
```


2つ目のリダイレクトのワイルドカードパラメーター`{*slug}`は、スラッシュを含む残りのパス全体を取得します。`/blog/2026/hello-world`は`https://blog.example.com/2026/hello-world`にリダイレクトされます。サイトのセクションを丸ごと別のドメインに移すときに便利です。

<a name="view-and-inertia-routes"></a>

### View and Inertia routes


紹介ページや、内容をすべてテンプレートに記述した料金ページなど、ロジックのないページもあります。表示するだけのハンドラーを設けると実質的に中身のない関数が増えるため、ルートから直接[view](/ja/rust/docs/views)または[Inertia](/ja/rust/docs/inertia)ページをレンダリングできます。ビュー名を`view`に、またはページコンポーネント名を`inertia`に渡してください。

```rust
route.view("/about", "about");
route.inertia("/pricing", "Pricing");
```


ビューに渡されるのは全ビューの共有データ（[shared with every view](/ja/rust/docs/views#sharing-data-with-all-views)）だけで、ページには[shared props](/ja/rust/docs/inertia#shared-data)だけが渡ります。追加データが必要ならハンドラーを書いてください。これらのルートとリダイレクトルートにはリンク先に指定するハンドラー（[link to](#routes-are-identified-by-their-handlers)）がないため、URIでリンクしてください。

<a name="listing-your-routes"></a>

### Listing your routes


`route:list` [console command](/ja/rust/docs/console)で、アプリケーションに定義したすべてのルートを一覧できます。

```shell
laravel route:list
```


コマンドにはオプションも指定できます。`-v`は各ルートのミドルウェアを表示し、`--json`はスクリプトなどのツール向けに一覧をJSONで出力します。一部のルートだけを表示するには、`--path=admin`でURIを、または`--handler=users`でハンドラーを絞り込んでください。

<a name="route-parameters"></a>

## Route parameters


ユーザーIDなど、URIの1つのセグメントを取り出すには、中括弧内にルートパラメーターを定義します。

```rust
route.get("/users/{user}", users::show);
route.get("/posts/{post}/comments/{comment}", comments::show);
```


ハンドラーは`Params`エクストラクターでパラメーターを受け取ります。各値は`u64`や`String`などの指定した型に解析されます。複数のパラメーターはURIに現れる順にタプルとして渡されます。

```rust
use laravel::prelude::*;

pub async fn show(Params(id): Params<u64>) -> String {
    format!("User {id}")
}

pub async fn show_comment(Params((post, comment)): Params<(u64, u64)>) -> String {
    format!("Comment {comment} on post {post}")
}
```


`u64`型に`/users/taylor`が渡された場合など、値を指定の型として解析できないと、リクエストには`404`が返り、ハンドラーは実行されません。


`{*path}`と書くワイルドカードパラメーターは、スラッシュを含むURIの残りすべてを取得します。

```rust
route.get("/files/{*path}", files::show);
```


1つのURIに複数のルートが一致すると、Laravelはセグメントを順に比較します。`create`のような固定セグメントは`{user}`などのパラメーターより優先され、パラメーターは`{*path}`などのワイルドカードより優先されます。`/users/{user}`を先に登録しても、`/users/create`は`/users/create`ルートに到達します。

<a name="optional-parameters"></a>

### Optional parameters


パラメーター名に`?`を付けると、そのセグメントを省略できます。省略可能なパラメーターはURIの末尾に配置してください。

```rust
route.get("/archive/{year?}/{month?}", archive::show);
```


このルートは`/archive`、`/archive/2026`、`/archive/2026/10`に一致します。省略可能な各パラメーターを`Option`型にし、ハンドラー内でデフォルト値を決めてください。このハンドラーは名前付きの構造体フィールドでパラメーターを受け取るため、`params.year`と`params.month`を取り違えずに済みます。

```rust
use laravel::prelude::*;

#[derive(Deserialize)]
pub struct ArchiveParams {
    year: Option<u16>,
    month: Option<u8>,
}

pub async fn show(Params(params): Params<ArchiveParams>) -> String {
    match params.year {
        Some(year) => format!("Archive for {year}, month {:?}", params.month),
        None => "All archives".to_owned(),
    }
}
```


タプルも使用でき、パラメーターが1つか2つなら短く書けます。たとえば`/archive/{year}/{month?}`には`Params<(u16, Option<u8>)>`が適合します。

<a name="restricting-parameter-values"></a>

### Restricting parameter values


指定した型に解析できないパラメーターには`404`が返るため、選んだ型がそのままパラメーターの制約になります。店舗のカテゴリーなど、決まった値だけを受け付ける場合は、列挙型で受け取ります。

```rust
use laravel::prelude::*;

#[derive(Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum Category {
    Movies,
    Songs,
    Paintings,
}

pub async fn show(Params(category): Params<Category>) -> &'static str {
    match category {
        Category::Movies => "Movies",
        Category::Songs => "Songs",
        Category::Paintings => "Paintings",
    }
}
```


このハンドラーを`/categories/{category}`に登録すると、`/categories/songs`はハンドラーに到達し、`/categories/podcasts`には`404`が返ります。

<a name="records-in-route-parameters"></a>

### Models in route parameters


`/posts/{post}`の投稿IDのようにパラメーターがモデルのキーを含む場合は、ハンドラーの引数に[model](/ja/rust/docs/models#route-model-binding)を指定します。Laravelはハンドラーを実行する前に、そのIDの投稿をデータベースから取得して渡します。投稿がなければ`404`を返し、ハンドラーは実行しません。

```rust
use crate::models::Post;

pub async fn show(post: Post) -> String {
    post.title
}
```


スラッグなど別のフィールドで投稿を取得するには、`/blog/{post:slug}`のようにコロンの後にフィールド名を書きます。ID以外でモデルを取得する方法は、モデルガイドの[customizing the key](/ja/rust/docs/models#customizing-the-key)を参照してください。


ミドルウェア内など、ハンドラーの引数以外でモデルを取得するには、パラメーター名を渡して`request.model`を呼び出します。

```rust
let post: Post = request.model("post").await?;
```


ハンドラーはモデルとほかのルートパラメーターを一緒に受け取れます。モデルは独立した引数で受け取り、残りは`Params`で受け取ってください。モデル用のパラメーターを除いて必要なものだけを名前で指定できるので、ここでは構造体が適しています。`/posts/{post}/comments/{sort}`のルートを例に挙げます。

```rust
use laravel::prelude::*;

use crate::models::Post;

#[derive(Deserialize)]
pub struct CommentParams {
    sort: String,
}

pub async fn index(post: Post, Params(params): Params<CommentParams>) -> String {
    format!("Comments on {}, sorted by {}", post.title, params.sort)
}
```

<a name="routes-are-identified-by-their-handlers"></a>

## Linking to routes


ルートへのリンクには、登録時に指定した関数、つまりハンドラーを使います。ハンドラーやミドルウェア内では、`route!`または`redirect!`にハンドラーと必要なパラメーターを渡してください。どちらも[prelude](/ja/rust/docs/prelude)にあります。

```rust
let url = route!(users::show, 1)?; // http://localhost/users/1

let response = redirect!(users::show, 1);
```


IDの代わりにモデルを渡せます。Laravelはモデルのルートキーをパラメーターに入れます。[customized the key](/ja/rust/docs/models#customizing-the-key)に従ってキーを変更していない限り、モデルのIDが使われます。

```rust
let url = route!(posts::show, &post)?; // http://localhost/posts/42

let response = redirect!(posts::show, &post);
```


複数のパラメーターを持つルートには、URIに現れる順に渡すか、`key = value`で名前を指定して渡します。

```rust
// http://localhost/posts/42/comments/7
let url = route!(comments::show, &post, &comment)?;
```


リンク先はハンドラーなので、ルートのURIを変更してもリンク元のコードを変更する必要はありません。ハンドラーを改名または削除すると、それを使い続けているすべての`route!`と`redirect!`の呼び出し箇所をコンパイラーが示します。


[template](/ja/rust/docs/templates#urls)でURLを生成するには、`route`に`route:list`の出力と同じ表記のハンドラーパスを渡し、続けてルートパラメーターを渡します。

```html
<a href="{{ route("posts::show", post) }}">{{ post.title }}</a>
```


クエリ文字列の追加や署名付きURLの作成など、URL生成の詳細は[URL generation documentation](/ja/rust/docs/urls)を参照してください。

<a name="route-groups"></a>

## Route groups


ルートグループを使うと、プレフィックスやミドルウェアなどの属性を各ルートに繰り返し書かずに共有できます。グループの中に別のグループを置くこともできます。内側のグループのプレフィックスは外側のプレフィックスの後に付き、内側のルートは両グループのミドルウェアを実行します。

<a name="prefixes"></a>

### Prefixes


`prefix`メソッドはグループ内の各ルートにURIプレフィックスを付けます。たとえばすべての管理ルートを`/admin`で始めることができます。

```rust
route.prefix("/admin").group(|route| {
    route.get("/users", admin::users::index); // Matches "/admin/users"...
});
```

<a name="middleware"></a>

### Middleware


グループのすべてのルートに[middleware](/ja/rust/docs/middleware)を適用するには、`group`の前で`middleware`を呼び出します。ほかの属性とも組み合わせられます。

```rust
use laravel::auth::Authenticate;

route.prefix("/admin").middleware(Authenticate).group(|route| {
    route.get("/", admin::dashboard);
    route.get("/reports", admin::reports);
});
```


個々のルートにもミドルウェアを指定できます。グループ内では、グループのミドルウェアの後でルート独自のミドルウェアを実行します。ここでは、すべての管理ページでログインが必要になり、請求ページではさらにメールアドレスの認証が必要になります。

```rust
use laravel::auth::{Authenticate, RequireVerifiedEmail};

route.prefix("/admin").middleware(Authenticate).group(|route| {
    route.get("/", admin::dashboard);
    route.get("/billing", admin::billing).middleware(RequireVerifiedEmail);
});
```


グループ内の特定のルートでグループのミドルウェアの一部を実行したくないときは、そのルートで`without_middleware`を呼び出します。次のステータスページは`/admin`の下にありますが、誰でも閲覧できます。

```rust
route.prefix("/admin").middleware(Authenticate).group(|route| {
    route.get("/", admin::dashboard);
    route.get("/status", admin::status).without_middleware::<Authenticate>();
});
```


`without_middleware`は、CSRF保護など`web`や`api`グループが提供するミドルウェアにも使えます。`group`の前に呼び出せばグループ全体に適用されます。詳しくはミドルウェアガイドの[excluding middleware](/ja/rust/docs/middleware#excluding-middleware)を参照してください。

<a name="domain-routing"></a>

### Domain routing


`domain`を使うとグループを特定のホストに限定できます。マルチテナントアプリケーションの顧客アカウントなど、ホストの一部をドメインのパラメーターとして取得できます。

```rust
route.domain("admin.example.com").group(|route| {
    route.get("/dashboard", admin::dashboard);
});

route.domain("{account}.example.com").group(|route| {
    route.get("/users/{user}", users::show);
});
```


2つ目のグループは`acme.example.com/users/42`に一致します。ハンドラーはドメインのアカウントとパスのユーザーを一緒に受け取ります。ドメインパラメーターが先に渡されます。

```rust
use laravel::prelude::*;

pub async fn show(Params((account, user)): Params<(String, u64)>) -> String {
    format!("User {user} on the {account} account")
}
```


ドメイン指定のあるルートは、指定のないルートより優先されます。ドメイン指定のあるルート同士では先に登録したものが優先されるため、`{account}.example.com`のようなパターンより先に個別のホストを登録してください。

> [!WARNING]
> 本番環境では、Laravelは`APP_URL`のホストとそのサブドメイン宛てのリクエストにだけ応答します。`APP_URL`が`https://example.com`のときに`example.org`を使うなど、ドメインルートが別のドメインを使う場合は、そのドメインを[trusted hosts](/ja/rust/docs/middleware#trusting-hosts)に追加してください。追加しないとLaravelはそのリクエストを`400`で拒否します。


これらのドメインのルートにリンクするには、ドメインパラメーターを先に、続いてパスパラメーターを渡してください。

```rust
let url = route!(users::show, "acme", 42)?; // http://acme.example.com/users/42
```


詳しくはURL生成ガイドの[domain parameters](/ja/rust/docs/urls#domain-parameters)を参照してください。

<a name="head-metadata"></a>

### Head metadata


`with_head`で、タイトルなどルートやグループの[head metadata](/ja/rust/docs/head)を設定できます。

```rust
use laravel::head::{Head, Robots};

route.get("/", welcome::show).with_head(Head::new().title("Welcome"));

route.with_head(Head::new().robots(Robots::None)).prefix("/admin").group(|route| {
    route.get("/dashboard", admin::dashboard).with_head(Head::new().title("Dashboard"));
});
```


タイトルなど同じタグがルートとグループの両方に設定されている場合、Laravelはルートの値を使います。ハンドラーは[`head::merge`](/ja/rust/docs/head)を呼び出し、自分のページのタグを個別に変更できます。

<a name="resource-routes"></a>

## Resource routes


多くのアプリケーションでは、複数のモデルが作成・参照・更新・削除（CRUD）用の共通のルート構成を必要とします。たとえば写真ギャラリーには一覧ページ、アップロードフォーム、1枚の写真を表示するページ、編集・削除用ルートが必要です。モデルごとに7つのルートを繰り返し登録せずに済むよう、Laravelはまとめて登録できます。各アクションの名前を持つ[handlers](/ja/rust/docs/handlers)をモジュールに定義し、そのモジュールを`resource!`で登録してください。

```rust
use laravel::routing::resource;

use crate::http::handlers::photos;

pub fn routes(route: &mut Router) {
    resource!(photos);
}
```


`photos`内の公開関数には、アクション名と一致すれば対応するルートが割り当てられます。

| メソッド | URI | ハンドラー |
| --- | --- | --- |
| `GET` | `/photos` | `photos::index` |
| `GET` | `/photos/create` | `photos::create` |
| `POST` | `/photos` | `photos::store` |
| `GET` | `/photos/{photo}` | `photos::show` |
| `GET` | `/photos/{photo}/edit` | `photos::edit` |
| `PUT`, `PATCH` | `/photos/{photo}` | `photos::update` |
| `DELETE` | `/photos/{photo}` | `photos::destroy` |


APIモジュールのように`create`や`edit`がないモジュールには、残りのルートだけが登録されます。


これらも通常のルートなので、ハンドラーは写真を[model](#records-in-route-parameters)として受け取れます。Laravelは`{photo}`パラメーターで写真を取得し、なければ`404`を返します。モデル自体を渡してルートへリンクすることもできます。

```rust
// src/http/handlers/photos.rs
use crate::models::Photo;

pub async fn show(photo: Photo) -> String {
    photo.title
}
```

```rust
let url = route!(photos::show, &photo)?; // http://localhost/photos/42
```


リソース名にはモジュール名のアンダースコアをハイフンに置き換えたものを使うため、`blog_posts`のルートは`/blog-posts/{blog_post}`になります。パラメーター名は単数形なので、`photos`には`{photo}`、`categories`には`{category}`が使われます。

<a name="partial-resources"></a>

### Register only some actions


リソースの一部のルートだけが必要な場合もあります。たとえば請求書は一覧と詳細を閲覧できても編集できない場合があります。`use`宣言と同じように、必要なアクションを列挙してください。大半のアクションが必要なら、`except`で不要なものだけを指定するほうが簡潔です。ここでは`create`と`edit`のフォームを除くすべての写真ルートを登録します。

```rust
use laravel::routing::{Action, resource};

resource!(invoices::{index, show});
resource!(photos).except([Action::Create, Action::Edit]);
```

<a name="nested-resources"></a>

### Nest a resource in its parent's module


別のリソースの中でのみ意味を持つリソースもあります。たとえば写真ギャラリーのコメントは必ずいずれかの写真に付きます。写真42のコメント一覧は`/photos/42/comments`、個々のコメントは`/photos/42/comments/7`で表示します。このような入れ子のリソースは、親モジュール内のモジュールにハンドラーを置きます。コメントのハンドラーは`src/http/handlers/photos/comments.rs`に置き、写真モジュールから宣言します。

```rust
// src/http/handlers/photos.rs
pub mod comments;
```


次に入れ子のモジュールを登録します。Laravelは両方のモジュールから各URIを組み立てます。

```rust
resource!(photos::comments);
```

| メソッド | URI | ハンドラー |
| --- | --- | --- |
| `GET` | `/photos/{photo}/comments` | `photos::comments::index` |
| `GET` | `/photos/{photo}/comments/create` | `photos::comments::create` |
| `POST` | `/photos/{photo}/comments` | `photos::comments::store` |
| `GET` | `/photos/{photo}/comments/{comment}` | `photos::comments::show` |
| `GET` | `/photos/{photo}/comments/{comment}/edit` | `photos::comments::edit` |
| `PUT`, `PATCH` | `/photos/{photo}/comments/{comment}` | `photos::comments::update` |
| `DELETE` | `/photos/{photo}/comments/{comment}` | `photos::comments::destroy` |


ハンドラーは写真とコメントの両方をモデルとして受け取れます。Laravelは`{photo}`から写真を、`{comment}`からコメントを取得します。

```rust
// src/http/handlers/photos/comments.rs
use crate::models::{Comment, Photo};

pub async fn show(photo: Photo, comment: Comment) -> String {
    format!("{} on {}", comment.body, photo.title)
}
```


コメント作成後は、多くの場合、写真IDを前に付けずにコメント自身のIDだけで取得できます。その場合にURIを短くするには`shallow`を呼び出します。個々のコメントのルートでは写真を省略しますが、一覧と作成のルートではどの写真のコメントかを知る必要があるため、写真を残します。

```rust
resource!(photos::comments).shallow();
```

| メソッド | URI | ハンドラー |
| --- | --- | --- |
| `GET` | `/photos/{photo}/comments` | `photos::comments::index` |
| `GET` | `/photos/{photo}/comments/create` | `photos::comments::create` |
| `POST` | `/photos/{photo}/comments` | `photos::comments::store` |
| `GET` | `/comments/{comment}` | `photos::comments::show` |
| `GET` | `/comments/{comment}/edit` | `photos::comments::edit` |
| `PUT`, `PATCH` | `/comments/{comment}` | `photos::comments::update` |
| `DELETE` | `/comments/{comment}` | `photos::comments::destroy` |


ハンドラーのフォルダーが必ずしも親リソースを表すとは限りません。たとえば管理ページが`src/http/handlers/admin/`にある場合、`resource!(admin::users)`は`admin`を親として扱い、`/admin/{admin}/users`を登録します。`admin`は実際のリソースではないので、モジュールをインポートし、[group](#prefixes)で`/admin`プレフィックスを追加してください。

```rust
use crate::http::handlers::admin::users;

route.prefix("/admin").group(|route| {
    resource!(users); // /admin/users, /admin/users/{user}, ...
});
```

<a name="single-resources"></a>

### Mark a resource as single


複数の項目の集合ではないリソースもあります。ユーザーのプロフィールは1つだけなので、URIにIDは不要です。`/profile`でログイン中のユーザーのプロフィールを、`/profile/edit`でその編集フォームを表示します。このようにURIにIDのないリソースを登録するには、`single`を呼び出します。

```rust
resource!(profile).single();
```


`profile`モジュールに`show`、`edit`、`update`のハンドラーがあれば、次のルートが登録されます。

| メソッド | URI | ハンドラー |
| --- | --- | --- |
| `GET` | `/profile` | `profile::show` |
| `GET` | `/profile/edit` | `profile::edit` |
| `PUT`, `PATCH` | `/profile` | `profile::update` |


単一のリソースは一覧にする項目が1つしかないため、`index`以外のアクションを利用できます。

<a name="resource-middleware"></a>

### Add middleware to some actions


`resource!`はリソースのルートを返すので、`middleware`で全ルートに[middleware](/ja/rust/docs/middleware)を適用したり、`middleware_for`で特定のアクションにだけ適用したりできます。一部のアクションをグループの特定のミドルウェアから除外するには`without_middleware_for`を呼び出します。この例では誰でも写真を閲覧できますが、アップロード、編集、削除はメールアドレスを認証したログイン中のユーザーだけに許可されます。

```rust
use laravel::auth::{Authenticate, RequireVerifiedEmail};
use laravel::routing::{Action, resource};

route.middleware(Authenticate).group(|route| {
    resource!(photos)
        .middleware_for(
            [Action::Store, Action::Update, Action::Destroy],
            RequireVerifiedEmail,
        )
        .without_middleware_for::<Authenticate>([Action::Index, Action::Show]);
});
```

<a name="fallback-routes"></a>

## Fallback routes


フォールバックがない場合、どのルートにも一致しないリクエストには`404`ページが返ります。`fallback`メソッドで、これらのリクエストを処理するルートを定義できます。

```rust
route.fallback(pages::not_found);
```


アプリケーションのフォールバック`async || laravel::abort(404)`は、未知のページをInertiaの[error page](/ja/rust/docs/errors#error-pages)で表示します。Webルートファイル内のフォールバックは、同じファイルのほかのルートと同様に`web`ミドルウェアグループを実行します。フォールバックの対象はグループのプレフィックス配下のURIに限られます。たとえばAPIのフォールバックが`/api/..`を担当し、残りをWebのフォールバックが担当します。

<a name="static-files"></a>

`public`ディレクトリにリクエストと一致するファイルがあれば、Laravelはフォールバックに渡す前にそのファイルを配信します。

<a name="form-method-spoofing"></a>

## Form method spoofing


HTMLフォームから送信できるのは`GET`と`POST`リクエストだけです。フォームから`PUT`、`PATCH`、`DELETE`ルートを呼び出すには、非表示の`_method`フィールドを追加します。Laravelはその値をリクエストメソッドとして使います。

```html
<form action="/posts/1" method="POST">
    <input type="hidden" name="_method" value="DELETE">
    {{ csrf_field() }}
</form>
```


ファイルアップロード用フォームでは、ファイル入力項目より前に`_method`を置いてください。[Inertia](/ja/rust/docs/inertia)などのJavaScriptクライアントは実際の`PUT`、`PATCH`、`DELETE`リクエストを送れるため、`_method`は不要です。

<a name="accessing-the-current-route"></a>

## Accessing the current route


一部のページだけに適用する[middleware](/ja/rust/docs/middleware)など、ハンドラー以外のコードでも一致したルートを知りたい場合があります。リクエストからドメインまたはパスのパラメーターを読むには、`request.route`を呼び出します。値は文字列として返り、該当するパラメーターがルートになければ`None`が返ります。

```rust
if let Some(account) = request.route("account") {
    tracing::info!(account, "Serving an account page");
}
```


数値など別の型でパラメーターを受け取るには、その型を指定して`route_as`を使います。ハンドラーの`Params`と同様、値が型に合わない場合は`404`が返ります。

```rust
let user_id: u64 = request.route_as("user")?;
```


`current_route`メソッドはリクエストに一致したルートを返し、`route_is`は指定したハンドラーがそのリクエストを処理するかどうかを示します。

```rust
if let Some(route) = request.current_route() {
    route.uri();     // "/users/{user}"
    route.handler(); // "app::http::handlers::users::show"
}

if request.route_is(users::show) {
    // ...
}
```


グローバルミドルウェアはルーティングの前に実行されるため、そこでは`current_route()`が`None`を返します。ルートミドルウェアとハンドラーからは一致したルートを参照できます。

<a name="cors"></a>

## CORS


別のドメインのJavaScriptがアプリケーションを呼び出すとき、たとえばシングルページアプリがAPIを呼ぶとき、ブラウザはまず呼び出しが許可されているかを確認します。Laravelは[configuration](/ja/rust/docs/configuration)の`cors`セクションに従い、こうしたオリジン間リソース共有（CORS）のリクエストに応答します。デフォルトでは、すべてのオリジンから`api/*`配下のルートを呼び出せます。


アプリケーションを呼び出せるオリジンを変更するには、`src/config/cors.rs`の[configuration file](/ja/rust/docs/configuration#config-files)を編集します。この例では`webhooks/*`パスを追加し、`https://app.example.com`だけを許可して、リクエストでCookieを送信できるようにします。

```rust
// src/config/cors.rs
use laravel::config;
use laravel::config::cors::{Allowed, Cors};
use laravel::time::ToSpan;

#[config::section]
fn cors() -> Cors {
    Cors {
        paths: vec!["api/*".to_owned(), "webhooks/*".to_owned()],
        methods: Allowed::Any,
        origins: Allowed::only(["https://app.example.com"]),
        origin_patterns: Vec::new(),
        headers: Allowed::Any,
        exposed_headers: Vec::new(),
        max_age: Some(0.seconds().into()),
        credentials: true,
    }
}
```

| フィールド | 許可する内容 | デフォルト |
| --- | --- | --- |
| `paths` | オリジン間リクエストに応答するパス。`*`はワイルドカード | `api/*` |
| `origins` | アプリケーションを呼び出せるオリジン。`*`はワイルドカード。例：`https://*.example.com` | すべて |
| `origin_patterns` | ほかのオリジンを指定する正規表現。例：`OriginPattern::new(r"https://pr-\d+\.preview\.dev")` | なし |
| `methods` | 使用できるメソッド | すべて |
| `headers` | 送信できるリクエストヘッダー | すべて |
| `exposed_headers` | JavaScriptから読み取れるレスポンスヘッダー | なし |
| `max_age` | ブラウザがプリフライトの応答をキャッシュできる期間 | なし |
| `credentials` | リクエストでCookieを送信できるかどうか | `false` |

<a name="the-health-route"></a>

## The health route


アプリケーションは`src/app.rs`で設定した`/up`で、ロードバランサーや稼働監視サービスからのヘルスチェックに応答します。

```rust
.with_routing(|routing, _| {
    routing
        .web(routes::web::routes)
        .api(routes::api::routes)
        .health("/up");
})
```


アプリケーションが起動すると`200`を返し、パッケージの起動チェックの失敗などで起動できなければ`503`を返します。すべてのミドルウェアより前に実行されるため、IPアドレスによる疎通確認も機能します。


ヘルスチェック用のルートはデータベースを確認しません。データベース停止中はアプリケーションがリクエストを処理すべきでない場合、`src/app.rs`の`booted`コールバックでデータベースに問い合わせてください。クエリが失敗するとアプリケーションは起動しません。

```rust
use laravel::db;

Application::configure()
    .booted(async |_| {
        db::query!("SELECT 1").statement().await?;

        Ok(())
    })
```