> ## Documentation Index
> Fetch the complete documentation index at: https://kawax.biz/llms.txt
> Use this file to discover all available pages before exploring further.

# レスポンス

> Laravel for Rust のレスポンス作成、リダイレクト、ファイル、ストリーミングレスポンスを解説します。

## はじめに

アプリケーションのすべてのルートとハンドラーは、ユーザーのブラウザや API クライアントへ送り返す HTTP レスポンスを返します。Laravel は、`IntoResponse` を実装するすべての値を完全なレスポンスへ変換するため、HTTP レスポンスを手作業で構築する必要はめったにありません。

ハンドラーがプレーンテキスト、JSON、レンダリングされたビュー、リダイレクト、ファイルダウンロード、ライブストリームのいずれを返す場合でも、Laravel は、そのステータスコード、ヘッダー、ボディを処理します。

## レスポンスの作成

### 文字列と JSON

最も基本的なレスポンスは文字列で、Laravel はそれをプレーンテキストとして送ります。

```rust theme={null}
use laravel::prelude::*;

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

API を構築したり構造化されたデータを返したりする場合は、任意の `Serialize` 値を `Json` で包みます。Laravel はその値をシリアライズし、`Content-Type` ヘッダーを `application/json` に設定します。

```rust theme={null}
use laravel::prelude::*;

#[derive(Serialize)]
pub struct Health {
    pub status: &'static str,
    pub version: &'static str,
}

pub async fn health() -> Json<Health> {
    Json(Health {
        status: "ok",
        version: "1.0.0",
    })
}
```

構造体を定義するのが大げさに感じる、素早くアドホックな JSON ペイロードには、代わりに `serde_json::json!` を使えます。

```rust theme={null}
use laravel::prelude::*;
use serde_json::{Value, json};

pub async fn status() -> Json<Value> {
    Json(json!({
        "status": "ok",
        "version": "1.0.0",
    }))
}
```

[モデル](https://laravel.com/rust/docs/models)は `Serialize` を実装するため、モデルやモデルのリストを `Json` で包んで返すこともできます。

```rust theme={null}
use laravel::prelude::*;

use crate::models::User;

pub async fn index() -> laravel::Result<Json<Vec<User>>> {
    let users = User::all().await?;

    Ok(Json(users))
}
```

`#[serde(skip)]` でマークされたフィールドは、JSON 出力から除外されます。アプリケーションの `User` モデルは、その `password` と `remember_token` フィールドをこの方法でスキップするため、それらは JSON レスポンスに公開されません。

### HTML

サーバーで HTML ページをレンダリングしたい場合は、[ビュー](https://laravel.com/rust/docs/views)を返します。

```rust theme={null}
use laravel::prelude::*;
use laravel::view::View;

pub async fn about() -> View {
    view("about", data! { company => "Laravel" })
}
```

ビルドステップが Markdown から生成する利用規約ページのように、すでに信頼する HTML を持っている場合があります。それをエスケープせずに HTML として送るには、`Html::raw` で包みます。

```rust theme={null}
use laravel::view::Html;

pub async fn terms() -> Html {
    Html::raw(include_str!("../../../resources/terms.html"))
}
```

### Inertia

別個の API を構築し保守することなく、React、Vue、Svelte でフロントエンドを構築したい場合は、サーバーレンダリングされたビューの代わりに、[Inertia](https://laravel.com/rust/docs/inertia) レスポンスを返せます。フロントエンドのページコンポーネントの名前とその props を `inertia::render` へ渡します。

```rust theme={null}
use laravel::inertia::{self, Page, props};

use crate::models::Post;

pub async fn show(post: Post) -> Page {
    inertia::render("Posts/Show", props! { post })
}
```

Inertia ページのレンダリング、データの共有、フロントエンドでのフォームの処理について詳しくは、[Inertia ガイド](https://laravel.com/rust/docs/inertia)を参照してください。

### Created とコンテンツなし

JSON API を構築する場合、通常、リソースを作成した後は `201 Created` で、削除した後は `204 No Content` で応答します。Laravel は、値を `201` ステータスで JSON としてシリアライズする `Created` と、空の `204` レスポンスを送る `NoContent` を提供します。

この `posts` ハンドラーモジュールでは、`NewPost` はその投稿の[フィル構造体](https://laravel.com/rust/docs/models#fill-structs)であり、`store` はログイン中のユーザーのためにその投稿を作成し、`destroy` は、そのルートが名指しする投稿を削除します。

```rust theme={null}
use laravel::http::{Created, NoContent};
use laravel::model::create;
use laravel::prelude::*;

use crate::models::{Post, User};

#[laravel::input(fills = Post)]
#[validate(authenticated)]
pub struct NewPost {
    #[validate(required, max_length(255))]
    pub title: String,
    #[validate(required)]
    pub body: String,
}

pub async fn store(
    Authenticated(user): Authenticated<User>,
    Valid(input): Valid<NewPost>,
) -> laravel::Result<Created<Post>> {
    let post = create!(Post { user: &user, ..input }).await?;

    Ok(Created(post))
}

pub async fn destroy(post: Post) -> laravel::Result<NoContent> {
    post.delete().await?;

    Ok(NoContent)
}
```

クライアントに、新しいリソースがどこにあるかも伝えたい場合は、その URL で `Location` ヘッダーを取り付けます。`Created` に `with_header` を呼ぶと、それは `Response` に変わるため、そのハンドラーは `laravel::Result<Response>` を返します。

```rust theme={null}
pub async fn store(
    Authenticated(user): Authenticated<User>,
    Valid(input): Valid<NewPost>,
) -> laravel::Result<Response> {
    let post = create!(Post { user: &user, ..input }).await?;

    let location = route!(posts::show, &post)?;

    Ok(Created(post).with_header("location", location))
}
```

### ステータスコードとヘッダー

バックグラウンドエクスポートをキューに入れた後の `202 Accepted` のように、ハンドラーが `200 OK` 以外のステータスコードで応答する必要がある場合があります。ステータスコードを設定するには、それをレスポンスボディとともにタプルで返します。

```rust theme={null}
use laravel::prelude::*;

pub async fn export() -> (StatusCode, &'static str) {
    // Queue the export...

    (StatusCode::ACCEPTED, "Your export is being prepared.")
}
```

任意のレスポンスのステータスコードは、`StatusCode` か数値のステータスコードを渡して、`with_status` でも変更できます。`View` と `Page` では、`with_status` はその具体的な型を保持します。

```rust theme={null}
pub async fn readiness() -> Response {
    "Database unavailable".with_status(StatusCode::SERVICE_UNAVAILABLE)
}
```

任意のレスポンスにヘッダーを取り付けるには、`with_header` を呼び、複数のヘッダーを一度に取り付けるには `with_headers` を呼びます。取り付けるヘッダーは、ビューの `Content-Type` のようなデフォルトを含む、同じ名前の既存のヘッダーを置き換えます。

```rust theme={null}
use laravel::prelude::*;
use laravel::view::View;

pub async fn feed() -> View {
    view("feed", data! {}).with_header("content-type", "application/rss+xml")
}

pub async fn show() -> View {
    view("reports.show", data! {}).with_headers([
        ("cache-control", "no-store"),
        ("x-frame-options", "DENY"),
    ])
}
```

ハンドラーの異なる分岐が異なる種類のレスポンスを返す場合、Rust は、そのハンドラーが単一の型を返すことを必要とします。`Response` を返し、各分岐に `.into_response()` を呼びます。そのハンドラーが `?` も使う場合は、`laravel::Result<Response>` を返し、各分岐を `Ok(..)` で包みます。

```rust theme={null}
use laravel::prelude::*;

pub async fn show(request: Request) -> Response {
    let report = json!({ "title": "Q3 Sales", "total": 1_200 });

    if request.wants_json() {
        return Json(report).into_response();
    }

    view("reports.show", data! { report }).into_response()
}
```

### Cookie

好みのカラーテーマのように、ハンドラーがユーザーのブラウザに小さな値を保存する必要がある場合があります。`with_cookie` で、送信されるすべてのレスポンスに Cookie を取り付けられ、`without_cookie` で Cookie を早期に期限切れにできます。

```rust theme={null}
use laravel::prelude::*;

pub async fn update_theme() -> Redirect {
    Redirect::back().with_cookie(("theme", "dark"))
}

pub async fn forget_theme() -> Redirect {
    Redirect::back().without_cookie("theme")
}
```

Cookie の有効期間、属性、Laravel が Cookie を暗号化する方法について詳しくは、[Cookie ガイド](https://laravel.com/rust/docs/cookies)を参照してください。

## リダイレクト

フォームを保存したりアクションを完了したりした後は、通常、ページを直接レンダリングするのではなく、ユーザーを別のページへ送ります。決済プロバイダーのチェックアウトページのような、パスや完全な URL へリダイレクトするには、`Redirect::to` を返します。ユーザーを、来たページへ戻すには、`Redirect::back()` を返します。

```rust theme={null}
use laravel::prelude::*;

pub async fn dashboard() -> Redirect {
    Redirect::to("/home/dashboard")
}

pub async fn update() -> Redirect {
    // Save the user's settings...

    Redirect::back()
}
```

送信されたフォームが無効な場合に、自分でリダイレクトして戻る必要はありません。[検証](https://laravel.com/rust/docs/validation#validation-responses)が、検証エラーとその以前の入力とともにユーザーをそのフォームへリダイレクトして戻すことで、それを処理します。

### ルートへのリダイレクト

アプリケーションのルートの1つへリダイレクトするには、[そのハンドラー](https://laravel.com/rust/docs/routing#routes-are-identified-by-their-handlers)を `redirect!` へ渡します（[prelude](https://laravel.com/rust/docs/prelude)で利用できます）。ルートパラメーターは [`route!`](https://laravel.com/rust/docs/urls#route-parameters) におけるのと同じように動作します。そのルートにパラメーターがない場合はそのハンドラーだけを渡し、モデルのような位置パラメーターを渡すか、名前付きの `key = value` ペアを渡します。このハンドラーは、[`NewPost`](#created-and-no-content) フォームから投稿を作成し、その新しい投稿のページへリダイレクトします。

```rust theme={null}
use laravel::model::create;
use laravel::prelude::*;

use crate::models::{Post, User};

pub async fn store(
    Authenticated(user): Authenticated<User>,
    Valid(input): Valid<NewPost>,
) -> laravel::Result<Redirect> {
    let post = create!(Post { user: &user, ..input }).await?;

    Ok(redirect!(posts::show, &post))
}
```

アクティブなタブやフィルターのようなクエリパラメーターをリダイレクトに取り付けるには、名前付きパラメーターを直接渡すか、任意の `Serialize` 値（キーバリューペアや構造体のようなもの）で `with_query` をチェーンします。投稿のコメントセクションのような、宛先ページの特定のセクションへユーザーをスクロールするには、`with_fragment` をチェーンします。たとえば、これは `/posts/42?tab=comments#reply` へリダイレクトします。

```rust theme={null}
redirect!(posts::show, &post)
    .with_query([("tab", "comments")])
    .with_fragment("reply")
```

マクロではなく関数が必要な場合は、`Redirect::route(handler, params)` を直接呼びます。

### フラッシュされたセッションデータでのリダイレクト

新しいページへリダイレクトすることと、[セッションへデータをフラッシュする](https://laravel.com/rust/docs/session#flash-data)ことは、フォームが保存されたことを確認するバナーを表示するように、よく一緒に行われます。次のリクエストのために値をフラッシュするには、そのリダイレクトに `with` をチェーンします。

```rust theme={null}
use laravel::prelude::*;

pub async fn update() -> Redirect {
    // Update the user's profile...

    Redirect::back().with("status", "Profile updated!")
}
```

フラッシュされた値は、次のリクエストのためにだけ利用できます。ビューは [`session("status")`](https://laravel.com/rust/docs/templates#session-data) でそれを読めます。`with` はその値をセッションに保存するため、それは `web` ミドルウェアグループのルートでのみ動作します。

Inertia ハンドラーからリダイレクトする場合は、[`inertia::flash`](https://laravel.com/rust/docs/inertia#flash-data) を使い、宛先ページがその `flash` フィールドにそのメッセージを受け取るようにします。Inertia ページは、`Redirect::with` からの値を、それを prop として渡す場合にのみ読めます。たとえば、[セッションキーを共有する](https://laravel.com/rust/docs/inertia#expired-pages)ことでです。

### 意図したページへのリダイレクト

ゲストが認証を必要とするページを訪れると、[`Authenticate`](https://laravel.com/rust/docs/authentication#redirecting-guests) は、その URL をセッションに保存し、それらをログインページへ送ります。ログインした後、`Redirect::intended` は、それらを元々リクエストしたページへ送ります。意図した URL がセッションに保存されていない場合は、渡したルートにフォールバックします。

```rust theme={null}
use laravel::prelude::*;

pub async fn store() -> Redirect {
    // Log the user in...

    Redirect::intended(dashboard::show, ())
}
```

### リダイレクトステータスコード

デフォルトでは、リダイレクトは `302 Found` ステータスコードで応答します。異なるステータスコードが必要な場合は、数値や `StatusCode` を `status` へ渡すか、`301 Moved Permanently` リダイレクトのために `permanent` を呼びます。

```rust theme={null}
Redirect::to("/login").status(303);

Redirect::to("/new-home").permanent();
```

アプリケーションが Inertia を使う場合、Laravel は、`PUT`、`PATCH`、`DELETE` リクエストの後に [`302` リダイレクトを自動的に `303` に変える](https://laravel.com/rust/docs/inertia#redirects)ため、自分でステータスを設定する必要はありません。

## ファイル

請求書や、その所有者だけが見るべきレポートのように、一部のファイルは公開アクセスできるべきではありません。ユーザーがアクセスできることを確認した後、ディスク上のファイルを、ハンドラーから `File` として返せます。

### ファイルダウンロード

ユーザーのブラウザにファイルをダウンロードさせるには、そのファイルのパスで `File::download` を返します。ブラウザは、`name` で別の名前を指定しない限り、ディスク上の名前でそのファイルを保存します。

```rust theme={null}
use laravel::http::File;

pub async fn report() -> File {
    File::download("storage/reports/q3.pdf").name("Q3 Report.pdf")
}
```

### ファイルレスポンス

画像や PDF のように、ファイルをダウンロードする代わりにブラウザに直接表示するには、`File::new` を返します。

```rust theme={null}
use laravel::http::File;
use laravel::prelude::*;

pub async fn invoice(Params(id): Params<u64>) -> File {
    File::new(format!("storage/invoices/{id}.pdf"))
}
```

`File::download` と `File::new` の両方について、Laravel は、そのファイルの拡張子から `Content-Type` ヘッダーを設定し、条件付きリクエストと範囲リクエストをサポートするため、ブラウザはそのファイルをキャッシュし、中断されたダウンロードを再開できます。そのファイルがディスク上に存在しない場合、Laravel は `404` で応答します。相対パスは、そのプロセスの作業ディレクトリではなく、アプリケーションの[ベースパス](https://laravel.com/rust/docs/configuration#the-base-path)に対して解決されます。

> [!WARNING]
>
> リクエストからの生のファイル名のような、信頼できないユーザー入力から `File` パスを直接構築してはいけません。`..` や先行する `/` を含むパスは、ユーザーがディスク上の任意のファイルを読めるようにする可能性があります。代わりに、型付き ID を使うか、データベースからそのパスを調べるか、[ファイルシステムディスク](https://laravel.com/rust/docs/filesystem)を通じてファイルを配信します。

ファイルが拡張子なしに保存されている場合は、`content_type` でそのコンテンツタイプを明示的に指定します。

```rust theme={null}
pub async fn avatar(Params(id): Params<u64>) -> File {
    File::new(format!("storage/avatars/{id}")).content_type("image/png")
}
```

一回限りのエクスポートのように、このレスポンスのためだけにディスク上に一時ファイルを生成した場合は、`delete_after_send` を呼び、Laravel がそれを送信した後にそのファイルを削除するようにします。

```rust theme={null}
pub async fn export() -> File {
    File::download("storage/exports/tmp-users.csv")
        .name("users.csv")
        .delete_after_send()
}
```

> [!NOTE]
>
> Laravel は、`public` ディレクトリの静的ファイルをルートなしに配信します。ルートが配信するかどうかを決める非公開ファイルには `File` を使います。

### 生成されたコンテンツのダウンロード

一時ファイルをまずディスクに書くことなく、CSV エクスポートのような生成されたコンテンツをダウンロードとして提供したい場合があります。そのファイル名と内容で `Download` を返すと、Laravel は、そのファイル名からコンテンツタイプを設定します。

```rust theme={null}
use laravel::http::Download;

use crate::models::User;

pub async fn export() -> laravel::Result<Download> {
    let users = User::all().await?;

    let mut csv = String::from("name,email\n");

    for user in users {
        csv.push_str(&format!("{},{}\n", user.name, user.email));
    }

    Ok(Download::new("users.csv", csv))
}
```

大きなエクスポートでは、ファイル全体をメモリに保持することは現実的ではありません。代わりに、モデルの `cursor` で行を読むような、チャンクの生成が失敗する可能性がある場合は、チャンクの[ストリーム](https://laravel.com/rust/docs/responses#streamed-responses)を `Download::try_stream` へ渡します。Laravel は、各チャンクを、それが生成されると送信します。

```rust theme={null}
use laravel::http::Download;
use laravel::stream::StreamExt;

use crate::models::User;

pub async fn export() -> Download {
    let rows = User::query()
        .cursor()
        .map(|row| row.map(|user| format!("{},{}\n", user.name, user.email)));

    Download::try_stream("users.csv", rows)
}
```

チャンクのストリームが失敗できない場合は、代わりに `Download::stream` を使います。

## ストリーミングレスポンス

AI モデルのトークンごとの返信や、デプロイのライブ出力のように、一部のレスポンスは生成に時間がかかります。レスポンス全体が準備できるまで待つ代わりに、ストリーミングレスポンスは、各チャンクを、それが利用可能になるとすぐにクライアントへ送ります。

非同期クロージャーからチャンクをストリーミングするには、`Streamed::channel` を返します。そのクロージャーは、ハンドラーが戻ると実行を開始し、`sender.send` でチャンクを送ります。

```rust theme={null}
use laravel::http::Streamed;

pub async fn deploy() -> Streamed {
    Streamed::channel(async |sender| {
        for step in ["Building", "Migrating", "Done"] {
            // Run the step...

            sender.send(format!("{step}\n")).await?;
        }

        Ok(())
    })
}
```

`sender.send` は、クライアントが切断すると失敗するため、`?` はそのクロージャーをきれいに止めます。そのクロージャーが他のエラーを返すと、Laravel はそれを[報告](https://laravel.com/rust/docs/errors#reporting-errors)し、そのレスポンスを突然閉じるため、クライアントは、そのストリームが途中で切れたことが分かります。

ストリーミングレスポンスは、デフォルトで `text/plain` を使います。別のコンテンツタイプを送るには、そのレスポンスに `content_type` をチェーンします。

```rust theme={null}
pub async fn answer() -> Streamed {
    Streamed::channel(async |sender| {
        sender.send("# Summary\n\n").await?;
        sender.send("Here is the streamed Markdown reply.").await?;

        Ok(())
    })
    .content_type("text/markdown")
}
```

> [!NOTE]
>
> Laravel は、ハンドラーが戻った後、そのレスポンスボディを送る前に、セッションを保存します。ストリーミングレスポンスを返す前にハンドラーで[セッション](https://laravel.com/rust/docs/session)の変更を行い、プロデューサークロージャーの中では行いません。

バイトや文字列の、失敗しない `Stream` をすでに持っている場合（または `stream!` で構築する場合）は、それを直接 `Streamed::new` へ渡します。`laravel::stream` モジュールは、必要となるストリームユーティリティを再エクスポートします。`map` や `filter` のようなメソッドのための `StreamExt` と、`yield` で非同期ストリームを構築するための `stream!` と `try_stream!` マクロを含みます。

フロントエンドでは、`@laravel/stream-react` や `@laravel/stream-vue` の `useStream` フックでストリーミングレスポンスを消費できます。フロントエンドのためにそのパッケージをインストールします。

```shell theme={null}
npm install @laravel/stream-react
```

`useStream` は `POST` リクエストを送るため、そのルートを、`route.post("/deploy", deploys::deploy)` のように、`src/routes/web.rs` で `route.post` で登録します。そのフックは、`web` グループが設定する `XSRF-TOKEN` Cookie から CSRF トークンを読みます。`send` を呼び出すと、そのフックは、入ってくる各チャンクを自動的に `data` へ追加します。

```tsx theme={null}
import { useStream } from "@laravel/stream-react";

export default function Deploy() {
    const { data, isFetching, isStreaming, send } = useStream("/deploy");

    return (
        <div>
            <pre>{data}</pre>
            {isFetching && <p>Connecting...</p>}
            <button onClick={() => send({})} disabled={isStreaming}>
                Deploy
            </button>
        </div>
    );
}
```

### ストリーミング JSON レスポンス

データベースのすべてのユーザーのように、大きなリストを JSON として返す必要がある場合、そのリスト全体を一度にメモリへ読み込むことは遅く、高くつくことがあります。代わりに、各アイテムを、それが到着するとシリアライズして送る `JsonStream` を返します。

モデルクエリの `cursor` のように、失敗する可能性があるストリームには `JsonStream::try_new` を使います。それはデータベースから一度に1行ずつ読みます。デフォルトでは、`JsonStream` は、それらのアイテムを JSON 配列として送ります。

```rust theme={null}
use laravel::http::JsonStream;

use crate::models::User;

pub async fn users() -> JsonStream {
    JsonStream::try_new(User::query().cursor()) // [{"id":1,...},...]
}
```

その配列を、最上位キーの下の JSON オブジェクトで包みたい場合は、そのストリームに `key` をチェーンします。

```rust theme={null}
pub async fn users() -> JsonStream {
    JsonStream::try_new(User::query().cursor()).key("users") // {"users":[{"id":1,...},...]}
}
```

クエリが途中で失敗すると、Laravel はそのエラーを[報告](https://laravel.com/rust/docs/errors#reporting-errors)し、そのレスポンスを突然終わらせるため、クライアントは、終わったように見えるリストではなく、不完全な JSON を目にします。ストリームが失敗できない場合は、代わりに `JsonStream::new` を使います。クエリカーソルを使う代わりに、失敗する可能性があるストリームを自分で構築するには、`laravel::stream` の `try_stream!` を使います。それは、ストリームボディの中で `?` を使い、各アイテムを、それが準備できると `yield` できます。

フロントエンドでは、`@laravel/stream-react` や `@laravel/stream-vue` の `useJsonStream` フックが、そのストリーミングレスポンスを読み、そのストリームが終わるとその JSON をパースします。

```tsx theme={null}
import { useJsonStream } from "@laravel/stream-react";

type User = {
    id: number;
    name: string;
    email: string;
};

export default function Users() {
    const { data, send } = useJsonStream<{ users: User[] }>("/users");

    return (
        <div>
            <ul>
                {data?.users.map((user) => (
                    <li key={user.id}>{user.name}</li>
                ))}
            </ul>
            <button onClick={() => send({})}>Load Users</button>
        </div>
    );
}
```

### イベントストリーム

ライブのジョブ進捗や、リストに追加された新しいタスクのように、サーバーで物事が起きるとページへ更新をプッシュしたい場合は、サーバー送信イベント（`text/event-stream`）を送るために `EventStream` を返します。非同期クロージャーを `EventStream::channel` へ渡し、各イベントに `sender.send(...)` を呼び、エラーには `?` を使います。送る各値は、テキスト、`Json`、`Html`、ビューのいずれかであり、Laravel はそれを、デフォルトで `update` イベントとして送ります。

```rust theme={null}
use laravel::http::sse::EventStream;
use laravel::prelude::*;
use laravel::task;
use serde_json::json;

use crate::models::Export;

pub async fn progress(mut export: Export) -> EventStream {
    EventStream::channel(async move |sender| {
        loop {
            sender.send(Json(json!({ "percent": export.percent }))).await?;

            if export.percent >= 100 {
                break;
            }

            task::sleep(1.seconds()).await;

            let Some(updated) = Export::find(export.id).await? else {
                break;
            };

            export = updated;
        }

        Ok(())
    })
}
```

`sender.send` は、クライアントが切断すると失敗するため、`?` はそのクロージャーをきれいに止めます。そのクロージャーが他のエラーを返すと、Laravel はそれを[報告](https://laravel.com/rust/docs/errors#reporting-errors)し、最後の `</stream>` イベントを送らずにそのストリームを終わらせます。

ブラウザが別々にリッスンできるカスタム名をイベントに与えたい場合は、そのデータを `Event` で包みます。

```rust theme={null}
use laravel::http::sse::Event;

sender.send(Event::new("export-progress", Json(json!({ "percent": export.percent })))).await?;
```

`StreamExt::map` で変換された [Redis サブスクリプション](https://laravel.com/rust/docs/redis#pubsub)のような、失敗しない `Stream` をすでに持っている場合は、それを直接 `EventStream::new` へ渡します。

フロントエンドでは、`@laravel/stream-react` や `@laravel/stream-vue` の `useEventStream` フックが、`update` イベントをリッスンし、各イベントが到着すると `message` を更新します。

```tsx theme={null}
import { useEventStream } from "@laravel/stream-react";

export default function Progress() {
    const { message } = useEventStream("/progress");

    return <div>{message}</div>;
}
```

そのストリームのイベントが尽きると、Laravel は、`</stream>` を含む最後の `update` イベントを送り、`@laravel/stream` フックが、そのストリームが終わったことを知るようにします。ブラウザの `EventSource` API でそのストリームを手動で消費する場合は、`</stream>` が到着したらその接続を閉じ、ブラウザが自動的に再接続しないようにします。

```js theme={null}
const source = new EventSource("/progress");

source.addEventListener("update", (event) => {
    if (event.data === "</stream>") {
        source.close();

        return;
    }

    console.log(event.data);
});
```

最後のイベントは `end_with` でカスタマイズでき、`without_end_event` で省略できます。

```rust theme={null}
EventStream::new(events).end_with(Event::new("done", "complete"));

EventStream::new(events).without_end_event();
```

イベントが到着しない間、Laravel は15秒ごとにコメントを送り、プロキシがその接続を閉じないようにします。

## 独自のレスポンス

アプリケーションの複数のハンドラーが同じ種類のレスポンスを返す場合、それを、`IntoResponse` を実装する独自の型で包めます。たとえば、バックグラウンド作業をキューに入れる API は、ペイロードを `202 Accepted` ステータスで JSON としてシリアライズする `Accepted` 型を定義するかもしれません。

```rust theme={null}
use laravel::prelude::*;

pub struct Accepted<T>(pub T);

impl<T: Serialize> IntoResponse for Accepted<T> {
    fn into_response(self) -> Response {
        (StatusCode::ACCEPTED, Json(self.0)).into_response()
    }
}
```

ハンドラーは、今や `Accepted(job)` を直接返せ、`Accepted` は `IntoResponse` を実装するため、`with_header`、`with_headers`、`with_cookie`、`without_cookie` も得ます。

## テスト

ルートが返すレスポンスをテストするには、テスト `Application` を通じてリクエストを送り、そのレスポンスにアサーションをチェーンします。たとえば、これらのテストは、`/feed` が RSS コンテンツタイプを返し、`/dashboard` が `/home/dashboard` へリダイレクトすることを確認します。

```rust theme={null}
use laravel::testing::prelude::*;

#[laravel::test]
async fn the_feed_is_rss(app: Application) {
    app.get("/feed")
        .await
        .assert_ok()
        .assert_header("content-type", "application/rss+xml");
}

#[laravel::test]
async fn the_old_dashboard_redirects(app: Application) {
    app.get("/dashboard").await.assert_redirect_to("/home/dashboard");
}
```

ステータスコード、ヘッダー、Cookie、リダイレクト、JSON レスポンスのアサーションについて詳しくは、テストガイドの[利用可能なアサーション](https://laravel.com/rust/docs/testing#available-assertions)の節を参照してください。リダイレクトが導くページを確認したい場合は、[リダイレクトの追跡](https://laravel.com/rust/docs/testing#following-redirects)を参照してください。


## Related topics

- [レスポンス](https://kawax.biz/jp/go/responses.md)
- [Laravel MCP](https://kawax.biz/jp/mcp.md)
- [パッケージのレスポンスMacroとHTTP契約](https://kawax.biz/jp/advanced/package-response-macros.md)
- [リクエストライフサイクル](https://kawax.biz/jp/lifecycle.md)


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.