# 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` 요청은 ID가 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](/rust/docs/handlers)를 가리킵니다. 라우트 파일에는 짧은 URI 목록만 남고 각 핸들러에는 한 페이지의 코드가 들어갑니다. 핸들러는 [request](/rust/docs/requests), [service](/rust/docs/container), [route parameters](#route-parameters) 등의 추출기를 인수로 받고 [response](/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`으로 등록한 라우트는 세션, 암호화된 쿠키, [CSRF protection](/rust/docs/csrf)를 제공하는 `web` [middleware group](/rust/docs/middleware#middleware-groups) 안에서 실행됩니다.


다른 애플리케이션, 스크립트, 서비스가 호출할 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`를 여러 번 호출하면 라우트를 여러 파일로 나눌 수 있습니다.


클로저의 두 번째 인수는 애플리케이션 설정이므로 특정 환경에서만 일부 라우트를 등록할 수 있습니다.

```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에는 이전 URI와 같은 파라미터를 사용할 수 있습니다.

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


두 번째 리디렉션의 와일드카드 파라미터 `{*slug}`는 슬래시를 포함해 나머지 경로 전체를 가져옵니다. 따라서 `/blog/2026/hello-world`는 `https://blog.example.com/2026/hello-world`로 리디렉션됩니다. 사이트의 한 섹션 전체를 다른 도메인으로 옮길 때 유용합니다.

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

### View and Inertia routes


소개 페이지나 모든 콘텐츠가 템플릿에 있는 요금 안내 페이지처럼 별도의 로직이 없는 페이지도 있습니다. 렌더링만 하는 핸들러를 작성하면 별다른 내용이 없는 함수가 생기므로 라우트 자체에서 [view](/rust/docs/views) 또는 [Inertia](/rust/docs/inertia) 페이지를 렌더링할 수 있습니다. 뷰 이름은 `view`에, 페이지 컴포넌트 이름은 `inertia`에 전달하세요.

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


뷰에는 모든 뷰에서 공유하는 데이터([shared with every view](/rust/docs/views#sharing-data-with-all-views))만 전달되고 페이지에는 [shared props](/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](/rust/docs/console)로 애플리케이션에 정의한 모든 라우트를 한눈에 확인할 수 있습니다.

```shell
laravel route:list
```


명령어에 옵션을 추가할 수도 있습니다. `-v`는 각 라우트의 미들웨어를 표시하고 `--json`은 스크립트나 도구에서 사용할 수 있게 목록을 JSON으로 출력합니다. 일부 라우트만 보려면 `--path=admin`로 URI를 필터링하거나 `--handler=users`로 핸들러를 필터링하세요.

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

## Route parameters


사용자 ID처럼 URI의 한 세그먼트를 가져오려면 중괄호 안에 라우트 파라미터를 정의하세요.

```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);
```


여러 라우트가 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(),
    }
}
```


튜플을 사용해도 됩니다. 파라미터가 한두 개일 때 더 간결합니다. 예를 들어 `/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](/rust/docs/models#route-model-binding)을 받으세요. Laravel은 핸들러를 실행하기 전에 해당 ID의 게시물을 데이터베이스에서 조회해 전달합니다. 해당 ID의 게시물이 없으면 `404`로 응답하고 핸들러를 실행하지 않습니다.

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

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


슬러그 등 다른 필드로 게시물을 찾으려면 `/blog/{post:slug}`처럼 콜론 뒤에 필드 이름을 쓰세요. ID 이외의 값으로 모델을 찾는 방법은 모델 가이드의 [customizing the key](/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](/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](/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](/rust/docs/templates#urls)에서 URL을 생성하려면 `route`에 `route:list` 출력에 나오는 표기대로 핸들러 경로를 전달하고 이어서 라우트 파라미터를 전달하세요.

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


쿼리 문자열 추가, 서명된 URL 생성 등 URL 생성 방법은 [URL generation documentation](/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](/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](/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);
});
```


두 번째 그룹은 `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](/rust/docs/middleware#trusting-hosts)에 추가하세요. 추가하지 않으면 Laravel이 해당 요청을 `400`으로 거부합니다.


이러한 도메인의 라우트로 링크할 때는 도메인 파라미터를 먼저 전달하고 그다음 경로 파라미터를 전달하세요.

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


자세한 내용은 URL 생성 가이드의 [domain parameters](/rust/docs/urls#domain-parameters)를 참고하세요.

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

### Head metadata


`with_head`로 제목 등 라우트나 그룹의 [head metadata](/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`](/rust/docs/head)를 호출해 해당 페이지의 태그를 개별적으로 변경할 수 있습니다.

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

## Resource routes


대부분의 애플리케이션에는 생성·조회·수정·삭제(CRUD)를 위한 같은 라우트 구성이 필요한 모델이 있습니다. 사진 갤러리를 예로 들면 사진 목록 페이지, 새 사진 업로드 폼, 사진 한 장을 보여 주는 페이지, 수정·삭제 라우트가 필요합니다. 모델마다 일곱 라우트를 등록하는 작업이 반복되므로 Laravel은 이를 한 번에 등록할 수 있게 합니다. 각 액션의 이름을 딴 [handlers](/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


목록을 이루지 않는 리소스도 있습니다. 사용자는 프로필을 하나씩만 갖기 때문에 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` |


단일 리소스는 목록에 표시할 항목이 하나뿐이므로 `index`를 제외한 모든 액션을 사용할 수 있습니다.

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

### Add middleware to some actions


`resource!`는 리소스의 라우트를 반환하므로 `middleware`로 모든 라우트에 [middleware](/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](/rust/docs/errors#error-pages)로 렌더링합니다. 웹 라우트 파일의 대체 라우트는 같은 파일의 다른 라우트처럼 `web` 미들웨어 그룹을 실행합니다. 대체 라우트는 소속 그룹의 접두사 아래에 있는 URI만 처리합니다. 예를 들어 API 대체 라우트는 `/api/..`를 처리하고 웹 대체 라우트는 그 밖의 요청을 처리합니다.

<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](/rust/docs/inertia)와 다른 JavaScript 클라이언트는 실제 `PUT`, `PATCH`, `DELETE` 요청을 보내므로 `_method`가 필요 없습니다.

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

## Accessing the current route


일부 페이지에만 적용하는 [middleware](/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](/rust/docs/configuration)의 `cors` 항목을 사용해 이러한 교차 출처 리소스 공유(CORS) 요청에 응답합니다. 기본적으로 모든 출처에서 `api/*` 아래의 라우트를 호출할 수 있습니다.


애플리케이션을 호출할 수 있는 출처를 변경하려면 `src/config/cors.rs` [configuration file](/rust/docs/configuration#config-files)을 편집하세요. 다음 예는 `webhooks/*` 경로를 추가하고 `https://app.example.com`만 허용하며, 요청에 쿠키를 실을 수 있게 합니다.

```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` | 브라우저가 사전 요청(preflight) 응답을 캐시할 수 있는 기간 | 없음 |
| `credentials` | 요청에 쿠키를 포함할 수 있는지 여부 | `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(())
    })
```