Responses
Introduction
Every route and handler in your application returns an HTTP response to send back to the user's browser or API client. You rarely need to build an HTTP response by hand, because Laravel converts any value that implements IntoResponse into a full response.
Whether a handler returns plain text, JSON, a rendered view, a redirect, a file download, or a live stream, Laravel takes care of the status code, headers, and body for you.
Creating responses
Strings and JSON
The most basic response is a string, which Laravel sends as plain text:
1use laravel::prelude::*;23pub fn routes(route: &mut Router) {4 route.get("/", async || "Hello World");5}1use laravel::prelude::*;23pub fn routes(route: &mut Router) {4 route.get("/", async || "Hello World");5}
When building an API or returning structured data, wrap any Serialize value in Json. Laravel serializes the value and sets the Content-Type header to application/json:
1use laravel::prelude::*;23#[derive(Serialize)]4pub struct Health {5 pub status: &'static str,6 pub version: &'static str,7}89pub async fn health() -> Json<Health> {10 Json(Health {11 status: "ok",12 version: "1.0.0",13 })14}1use laravel::prelude::*;23#[derive(Serialize)]4pub struct Health {5 pub status: &'static str,6 pub version: &'static str,7}89pub async fn health() -> Json<Health> {10 Json(Health {11 status: "ok",12 version: "1.0.0",13 })14}
For quick, ad-hoc JSON payloads where defining a struct feels like overkill, you may use serde_json::json! instead:
1use laravel::prelude::*;2use serde_json::{Value, json};34pub async fn status() -> Json<Value> {5 Json(json!({6 "status": "ok",7 "version": "1.0.0",8 }))9}1use laravel::prelude::*;2use serde_json::{Value, json};34pub async fn status() -> Json<Value> {5 Json(json!({6 "status": "ok",7 "version": "1.0.0",8 }))9}
Since models implement Serialize, you may also return a model or a list of models wrapped in Json:
1use laravel::prelude::*;23use crate::models::User;45pub async fn index() -> laravel::Result<Json<Vec<User>>> {6 let users = User::all().await?;78 Ok(Json(users))9}1use laravel::prelude::*;23use crate::models::User;45pub async fn index() -> laravel::Result<Json<Vec<User>>> {6 let users = User::all().await?;78 Ok(Json(users))9}
Any field marked #[serde(skip)] is left out of the JSON output. Your application's User model skips its password and remember_token fields this way, so they aren't exposed in JSON responses.
HTML
When you want to render an HTML page on the server, return a view:
1use laravel::prelude::*;2use laravel::view::View;34pub async fn about() -> View {5 view("about", data! { company => "Laravel" })6}1use laravel::prelude::*;2use laravel::view::View;34pub async fn about() -> View {5 view("about", data! { company => "Laravel" })6}
Sometimes you already have HTML that you trust, such as a terms of service page that your build step generates from Markdown. Wrap it in Html::raw to send it as HTML without escaping it:
1use laravel::view::Html;23pub async fn terms() -> Html {4 Html::raw(include_str!("../../../resources/terms.html"))5}1use laravel::view::Html;23pub async fn terms() -> Html {4 Html::raw(include_str!("../../../resources/terms.html"))5}
Inertia
If you'd like to build your frontend in React, Vue, or Svelte without building and maintaining a separate API, you may return an Inertia response instead of a server-rendered view. Pass the name of your frontend page component and its props to inertia::render:
1use laravel::inertia::{self, Page, props};23use crate::models::Post;45pub async fn show(post: Post) -> Page {6 inertia::render("Posts/Show", props! { post })7}1use laravel::inertia::{self, Page, props};23use crate::models::Post;45pub async fn show(post: Post) -> Page {6 inertia::render("Posts/Show", props! { post })7}
To learn more about rendering Inertia pages, sharing data, and handling forms on the frontend, check out the Inertia guide.
Created and no content
When building a JSON API, you'll usually respond with 201 Created after creating a resource and 204 No Content after deleting one. Laravel provides Created to serialize a value as JSON with a 201 status, and NoContent to send an empty 204 response.
In this posts handler module, NewPost is the post's fill struct, store creates the post for the logged-in user, and destroy deletes the post that the route names:
1use laravel::http::{Created, NoContent};2use laravel::model::create;3use laravel::prelude::*;45use crate::models::{Post, User};67#[laravel::input(fills = Post)]8#[validate(authenticated)]9pub struct NewPost {10 #[validate(required, max_length(255))]11 pub title: String,12 #[validate(required)]13 pub body: String,14}1516pub async fn store(17 Authenticated(user): Authenticated<User>,18 Valid(input): Valid<NewPost>,19) -> laravel::Result<Created<Post>> {20 let post = create!(Post { user: &user, ..input }).await?;2122 Ok(Created(post))23}2425pub async fn destroy(post: Post) -> laravel::Result<NoContent> {26 post.delete().await?;2728 Ok(NoContent)29}1use laravel::http::{Created, NoContent};2use laravel::model::create;3use laravel::prelude::*;45use crate::models::{Post, User};67#[laravel::input(fills = Post)]8#[validate(authenticated)]9pub struct NewPost {10 #[validate(required, max_length(255))]11 pub title: String,12 #[validate(required)]13 pub body: String,14}1516pub async fn store(17 Authenticated(user): Authenticated<User>,18 Valid(input): Valid<NewPost>,19) -> laravel::Result<Created<Post>> {20 let post = create!(Post { user: &user, ..input }).await?;2122 Ok(Created(post))23}2425pub async fn destroy(post: Post) -> laravel::Result<NoContent> {26 post.delete().await?;2728 Ok(NoContent)29}
If you'd also like to tell the client where the new resource lives, attach a Location header with its URL. Calling with_header on Created turns it into a Response, so the handler returns laravel::Result<Response>:
1pub async fn store(2 Authenticated(user): Authenticated<User>,3 Valid(input): Valid<NewPost>,4) -> laravel::Result<Response> {5 let post = create!(Post { user: &user, ..input }).await?;67 let location = route!(posts::show, &post)?;89 Ok(Created(post).with_header("location", location))10}1pub async fn store(2 Authenticated(user): Authenticated<User>,3 Valid(input): Valid<NewPost>,4) -> laravel::Result<Response> {5 let post = create!(Post { user: &user, ..input }).await?;67 let location = route!(posts::show, &post)?;89 Ok(Created(post).with_header("location", location))10}
Status codes and headers
Sometimes a handler needs to respond with a status code other than 200 OK, such as 202 Accepted after queuing a background export. To set a status code, return it in a tuple with your response body:
1use laravel::prelude::*;23pub async fn export() -> (StatusCode, &'static str) {4 // Queue the export...56 (StatusCode::ACCEPTED, "Your export is being prepared.")7}1use laravel::prelude::*;23pub async fn export() -> (StatusCode, &'static str) {4 // Queue the export...56 (StatusCode::ACCEPTED, "Your export is being prepared.")7}
You may also change the status code of any response with with_status, passing either a StatusCode or a numeric status code. On View and Page, with_status keeps the concrete type:
1pub async fn readiness() -> Response {2 "Database unavailable".with_status(StatusCode::SERVICE_UNAVAILABLE)3}1pub async fn readiness() -> Response {2 "Database unavailable".with_status(StatusCode::SERVICE_UNAVAILABLE)3}
To attach a header to any response, call with_header, or call with_headers to attach several headers at once. A header you attach replaces any existing header of the same name, including defaults such as a view's Content-Type:
1use laravel::prelude::*;2use laravel::view::View;34pub async fn feed() -> View {5 view("feed", data! {}).with_header("content-type", "application/rss+xml")6}78pub async fn show() -> View {9 view("reports.show", data! {}).with_headers([10 ("cache-control", "no-store"),11 ("x-frame-options", "DENY"),12 ])13}1use laravel::prelude::*;2use laravel::view::View;34pub async fn feed() -> View {5 view("feed", data! {}).with_header("content-type", "application/rss+xml")6}78pub async fn show() -> View {9 view("reports.show", data! {}).with_headers([10 ("cache-control", "no-store"),11 ("x-frame-options", "DENY"),12 ])13}
When different branches of a handler return different kinds of responses, Rust requires the handler to return a single type. Return Response and call .into_response() on each branch. If the handler also uses ?, return laravel::Result<Response> and wrap each branch in Ok(..):
1use laravel::prelude::*;23pub async fn show(request: Request) -> Response {4 let report = json!({ "title": "Q3 Sales", "total": 1_200 });56 if request.wants_json() {7 return Json(report).into_response();8 }910 view("reports.show", data! { report }).into_response()11}1use laravel::prelude::*;23pub async fn show(request: Request) -> Response {4 let report = json!({ "title": "Q3 Sales", "total": 1_200 });56 if request.wants_json() {7 return Json(report).into_response();8 }910 view("reports.show", data! { report }).into_response()11}
Cookies
Sometimes a handler needs to store a small value in the user's browser, such as their preferred color theme. You may attach a cookie to any outgoing response with with_cookie, and expire a cookie early with without_cookie:
1use laravel::prelude::*;23pub async fn update_theme() -> Redirect {4 Redirect::back().with_cookie(("theme", "dark"))5}67pub async fn forget_theme() -> Redirect {8 Redirect::back().without_cookie("theme")9}1use laravel::prelude::*;23pub async fn update_theme() -> Redirect {4 Redirect::back().with_cookie(("theme", "dark"))5}67pub async fn forget_theme() -> Redirect {8 Redirect::back().without_cookie("theme")9}
To learn more about cookie lifetimes, attributes, and how Laravel encrypts cookies, check out the cookies guide.
Redirects
After saving a form or completing an action, you'll usually send the user to another page rather than render one directly. To redirect to a path or a full URL, such as a payment provider's checkout page, return Redirect::to. To send the user back to the page they came from, return Redirect::back():
1use laravel::prelude::*;23pub async fn dashboard() -> Redirect {4 Redirect::to("/home/dashboard")5}67pub async fn update() -> Redirect {8 // Save the user's settings...910 Redirect::back()11}1use laravel::prelude::*;23pub async fn dashboard() -> Redirect {4 Redirect::to("/home/dashboard")5}67pub async fn update() -> Redirect {8 // Save the user's settings...910 Redirect::back()11}
You don't need to redirect back yourself when a submitted form is invalid. Validation handles that for you by redirecting the user back to the form with the validation errors and their previous input.
Redirecting to routes
To redirect to one of your application's routes, pass its handler to redirect! (available in the prelude). Route parameters work as they do in route!: pass the handler alone when the route has no parameters, pass positional parameters such as a model, or pass named key = value pairs. This handler creates a post from the NewPost form and redirects to the new post's page:
1use laravel::model::create;2use laravel::prelude::*;34use crate::models::{Post, User};56pub async fn store(7 Authenticated(user): Authenticated<User>,8 Valid(input): Valid<NewPost>,9) -> laravel::Result<Redirect> {10 let post = create!(Post { user: &user, ..input }).await?;1112 Ok(redirect!(posts::show, &post))13}1use laravel::model::create;2use laravel::prelude::*;34use crate::models::{Post, User};56pub async fn store(7 Authenticated(user): Authenticated<User>,8 Valid(input): Valid<NewPost>,9) -> laravel::Result<Redirect> {10 let post = create!(Post { user: &user, ..input }).await?;1112 Ok(redirect!(posts::show, &post))13}
To attach query parameters to a redirect, such as the active tab or a filter, pass named parameters directly or chain with_query with any Serialize value (such as key-value pairs or a struct). To scroll the user to a specific section of the destination page, such as the comments section of a post, chain with_fragment. For example, this redirects to /posts/42?tab=comments#reply:
1redirect!(posts::show, &post)2 .with_query([("tab", "comments")])3 .with_fragment("reply")1redirect!(posts::show, &post)2 .with_query([("tab", "comments")])3 .with_fragment("reply")
When you need a function rather than a macro, call Redirect::route(handler, params) directly.
Redirecting with flashed session data
Redirecting to a new page and flashing data to the session often go together, such as showing a banner that confirms a form was saved. To flash a value for the next request, chain with onto the redirect:
1use laravel::prelude::*;23pub async fn update() -> Redirect {4 // Update the user's profile...56 Redirect::back().with("status", "Profile updated!")7}1use laravel::prelude::*;23pub async fn update() -> Redirect {4 // Update the user's profile...56 Redirect::back().with("status", "Profile updated!")7}
The flashed value is available only for the next request. A view may read it with session("status"). Because with stores the value in the session, it only works on routes in the web middleware group.
When redirecting from an Inertia handler, use inertia::flash so the destination page receives the message in its flash field. An Inertia page can read a value from Redirect::with only if you pass it as a prop, for example by sharing a session key.
Redirecting to the intended page
When a guest visits a page that requires authentication, Authenticate stores that URL in the session and sends them to your login page. After they log in, Redirect::intended sends them on to the page they originally requested. If no intended URL was stored in the session, it falls back to the route you pass it:
1use laravel::prelude::*;23pub async fn store() -> Redirect {4 // Log the user in...56 Redirect::intended(dashboard::show, ())7}1use laravel::prelude::*;23pub async fn store() -> Redirect {4 // Log the user in...56 Redirect::intended(dashboard::show, ())7}
Redirect status codes
By default, redirects respond with a 302 Found status code. If you need a different status code, pass a number or a StatusCode to status, or call permanent for a 301 Moved Permanently redirect:
1Redirect::to("/login").status(303);2Redirect::to("/new-home").permanent();1Redirect::to("/login").status(303);2Redirect::to("/new-home").permanent();
If your application uses Inertia, Laravel automatically turns 302 redirects into 303 after PUT, PATCH, and DELETE requests, so you don't need to set the status yourself.
Files
Some files shouldn't be publicly accessible, such as invoices and reports that only their owner should see. After checking that the user has access, you may return a file on disk from your handler as a File.
File downloads
To prompt the user's browser to download a file, return File::download with the file's path. The browser saves the file under its name on disk unless you specify another name with name:
1use laravel::http::File;23pub async fn report() -> File {4 File::download("storage/reports/q3.pdf").name("Q3 Report.pdf")5}1use laravel::http::File;23pub async fn report() -> File {4 File::download("storage/reports/q3.pdf").name("Q3 Report.pdf")5}
File responses
To display a file directly in the browser instead of downloading it, such as an image or a PDF, return File::new:
1use laravel::http::File;2use laravel::prelude::*;34pub async fn invoice(Params(id): Params<u64>) -> File {5 File::new(format!("storage/invoices/{id}.pdf"))6}1use laravel::http::File;2use laravel::prelude::*;34pub async fn invoice(Params(id): Params<u64>) -> File {5 File::new(format!("storage/invoices/{id}.pdf"))6}
For both File::download and File::new, Laravel sets the Content-Type header from the file's extension and supports conditional and range requests, so browsers can cache the file and resume interrupted downloads. If the file doesn't exist on disk, Laravel responds with a 404. Relative paths resolve against your application's base path rather than the process's working directory.
Never build a File path directly from untrusted user input, such as a raw filename from the request. A path containing .. or a leading / could allow a user to read arbitrary files on disk. Use a typed ID, look up the path from your database, or serve files through a filesystem disk instead.
If a file is stored without an extension, specify its content type explicitly with content_type:
1pub async fn avatar(Params(id): Params<u64>) -> File {2 File::new(format!("storage/avatars/{id}")).content_type("image/png")3}1pub async fn avatar(Params(id): Params<u64>) -> File {2 File::new(format!("storage/avatars/{id}")).content_type("image/png")3}
If you generated a temporary file on disk solely for this response, such as a one-off export, call delete_after_send so Laravel removes the file once it's sent:
1pub async fn export() -> File {2 File::download("storage/exports/tmp-users.csv")3 .name("users.csv")4 .delete_after_send()5}1pub async fn export() -> File {2 File::download("storage/exports/tmp-users.csv")3 .name("users.csv")4 .delete_after_send()5}
Laravel serves static files in your public directory without a route. Use File for private files that your routes decide whether to serve.
Downloads of generated content
Sometimes you want to offer generated content as a download, such as a CSV export, without writing a temporary file to disk first. Return a Download with the filename and contents, and Laravel sets the content type from the filename:
1use laravel::http::Download;23use crate::models::User;45pub async fn export() -> laravel::Result<Download> {6 let users = User::all().await?;78 let mut csv = String::from("name,email\n");910 for user in users {11 csv.push_str(&format!("{},{}\n", user.name, user.email));12 }1314 Ok(Download::new("users.csv", csv))15}1use laravel::http::Download;23use crate::models::User;45pub async fn export() -> laravel::Result<Download> {6 let users = User::all().await?;78 let mut csv = String::from("name,email\n");910 for user in users {11 csv.push_str(&format!("{},{}\n", user.name, user.email));12 }1314 Ok(Download::new("users.csv", csv))15}
For a large export, holding the entire file in memory isn't practical. Instead, pass a stream of chunks to Download::try_stream when producing chunks can fail, such as reading rows with a model's cursor. Laravel sends each chunk as it's produced:
1use laravel::http::Download;2use laravel::stream::StreamExt;34use crate::models::User;56pub async fn export() -> Download {7 let rows = User::query()8 .cursor()9 .map(|row| row.map(|user| format!("{},{}\n", user.name, user.email)));1011 Download::try_stream("users.csv", rows)12}1use laravel::http::Download;2use laravel::stream::StreamExt;34use crate::models::User;56pub async fn export() -> Download {7 let rows = User::query()8 .cursor()9 .map(|row| row.map(|user| format!("{},{}\n", user.name, user.email)));1011 Download::try_stream("users.csv", rows)12}
If your stream of chunks can't fail, use Download::stream instead.
Streamed responses
Some responses take a while to produce, such as an AI model's reply that arrives token by token or the live output of a deployment. Instead of waiting until the entire response is ready, a streamed response sends each chunk to the client as soon as it's available.
To stream chunks from an async closure, return Streamed::channel. The closure starts running once your handler returns, and sends chunks with sender.send:
1use laravel::http::Streamed;23pub async fn deploy() -> Streamed {4 Streamed::channel(async |sender| {5 for step in ["Building", "Migrating", "Done"] {6 // Run the step...78 sender.send(format!("{step}\n")).await?;9 }1011 Ok(())12 })13}1use laravel::http::Streamed;23pub async fn deploy() -> Streamed {4 Streamed::channel(async |sender| {5 for step in ["Building", "Migrating", "Done"] {6 // Run the step...78 sender.send(format!("{step}\n")).await?;9 }1011 Ok(())12 })13}
sender.send fails once the client disconnects, so ? stops the closure cleanly. If the closure returns any other error, Laravel reports it and closes the response abruptly, so the client can tell the stream was cut short.
Streamed responses use text/plain by default. To send another content type, chain content_type onto the response:
1pub async fn answer() -> Streamed {2 Streamed::channel(async |sender| {3 sender.send("# Summary\n\n").await?;4 sender.send("Here is the streamed Markdown reply.").await?;56 Ok(())7 })8 .content_type("text/markdown")9}1pub async fn answer() -> Streamed {2 Streamed::channel(async |sender| {3 sender.send("# Summary\n\n").await?;4 sender.send("Here is the streamed Markdown reply.").await?;56 Ok(())7 })8 .content_type("text/markdown")9}
Laravel saves the session after your handler returns and before it sends the response body. Make any session changes in the handler before returning the streamed response, not inside the producer closure.
If you already have an infallible Stream of bytes or strings (or build one with stream!), pass it directly to Streamed::new. The laravel::stream module re-exports the stream utilities you'll need, including StreamExt for methods like map and filter and the stream! and try_stream! macros for building async streams with yield.
On the frontend, you may consume a streamed response with the useStream hook from @laravel/stream-react or @laravel/stream-vue. Install the package for your frontend:
1npm install @laravel/stream-react1npm install @laravel/stream-react
useStream sends a POST request, so register the route with route.post in src/routes/web.rs, such as route.post("/deploy", deploys::deploy). The hook reads the CSRF token from the XSRF-TOKEN cookie that the web group sets. Once you invoke send, the hook automatically appends each incoming chunk to data:
1import { useStream } from "@laravel/stream-react";23export default function Deploy() {4 const { data, isFetching, isStreaming, send } = useStream("/deploy");56 return (7 <div>8 <pre>{data}</pre>9 {isFetching && <p>Connecting...</p>}10 <button onClick={() => send({})} disabled={isStreaming}>11 Deploy12 </button>13 </div>14 );15}1import { useStream } from "@laravel/stream-react";23export default function Deploy() {4 const { data, isFetching, isStreaming, send } = useStream("/deploy");56 return (7 <div>8 <pre>{data}</pre>9 {isFetching && <p>Connecting...</p>}10 <button onClick={() => send({})} disabled={isStreaming}>11 Deploy12 </button>13 </div>14 );15}
Streamed JSON responses
When you need to return a large list as JSON, such as every user in your database, loading the entire list into memory at once can be slow and expensive. Instead, return a JsonStream, which serializes and sends each item as it arrives.
Use JsonStream::try_new with a stream that can fail, such as a model query's cursor, which reads one row at a time from the database. By default, JsonStream sends the items as a JSON array:
1use laravel::http::JsonStream;23use crate::models::User;45pub async fn users() -> JsonStream {6 JsonStream::try_new(User::query().cursor()) // [{"id":1,...},...]7}1use laravel::http::JsonStream;23use crate::models::User;45pub async fn users() -> JsonStream {6 JsonStream::try_new(User::query().cursor()) // [{"id":1,...},...]7}
If you'd rather wrap the array in a JSON object under a top-level key, chain key onto the stream:
1pub async fn users() -> JsonStream {2 JsonStream::try_new(User::query().cursor()).key("users") // {"users":[{"id":1,...},...]}3}1pub async fn users() -> JsonStream {2 JsonStream::try_new(User::query().cursor()).key("users") // {"users":[{"id":1,...},...]}3}
If the query fails part way, Laravel reports the error and ends the response abruptly, so the client sees incomplete JSON rather than a list that looks finished. If your stream can't fail, use JsonStream::new instead. To build a fallible stream yourself instead of using a query cursor, use try_stream! from laravel::stream, which lets you use ? inside the stream body and yield each item as it becomes ready.
On the frontend, the useJsonStream hook from @laravel/stream-react or @laravel/stream-vue reads the streamed response and parses the JSON once the stream finishes:
1import { useJsonStream } from "@laravel/stream-react";23type User = {4 id: number;5 name: string;6 email: string;7};89export default function Users() {10 const { data, send } = useJsonStream<{ users: User[] }>("/users");1112 return (13 <div>14 <ul>15 {data?.users.map((user) => (16 <li key={user.id}>{user.name}</li>17 ))}18 </ul>19 <button onClick={() => send({})}>Load Users</button>20 </div>21 );22}1import { useJsonStream } from "@laravel/stream-react";23type User = {4 id: number;5 name: string;6 email: string;7};89export default function Users() {10 const { data, send } = useJsonStream<{ users: User[] }>("/users");1112 return (13 <div>14 <ul>15 {data?.users.map((user) => (16 <li key={user.id}>{user.name}</li>17 ))}18 </ul>19 <button onClick={() => send({})}>Load Users</button>20 </div>21 );22}
Event streams
When you want to push updates to a page as things happen on the server, such as live job progress or new tasks added to a list, return an EventStream to send server-sent events (text/event-stream). Pass an async closure to EventStream::channel, call sender.send(...) for each event, and use ? for errors. Each value you send may be text, Json, Html, or a view, and Laravel sends it as an update event by default:
1use laravel::http::sse::EventStream;2use laravel::prelude::*;3use laravel::task;4use serde_json::json;56use crate::models::Export;78pub async fn progress(mut export: Export) -> EventStream {9 EventStream::channel(async move |sender| {10 loop {11 sender.send(Json(json!({ "percent": export.percent }))).await?;1213 if export.percent >= 100 {14 break;15 }1617 task::sleep(1.seconds()).await;1819 let Some(updated) = Export::find(export.id).await? else {20 break;21 };2223 export = updated;24 }2526 Ok(())27 })28}1use laravel::http::sse::EventStream;2use laravel::prelude::*;3use laravel::task;4use serde_json::json;56use crate::models::Export;78pub async fn progress(mut export: Export) -> EventStream {9 EventStream::channel(async move |sender| {10 loop {11 sender.send(Json(json!({ "percent": export.percent }))).await?;1213 if export.percent >= 100 {14 break;15 }1617 task::sleep(1.seconds()).await;1819 let Some(updated) = Export::find(export.id).await? else {20 break;21 };2223 export = updated;24 }2526 Ok(())27 })28}
sender.send fails once the client disconnects, so ? stops the closure cleanly. If the closure returns any other error, Laravel reports it and ends the stream without sending the final </stream> event.
If you'd like to give an event a custom name that the browser can listen for separately, wrap its data in an Event:
1use laravel::http::sse::Event;23sender.send(Event::new("export-progress", Json(json!({ "percent": export.percent })))).await?;1use laravel::http::sse::Event;23sender.send(Event::new("export-progress", Json(json!({ "percent": export.percent })))).await?;
If you already have an infallible Stream, such as a Redis subscription transformed with StreamExt::map, pass it directly to EventStream::new.
On the frontend, the useEventStream hook from @laravel/stream-react or @laravel/stream-vue listens for update events and updates message as each one arrives:
1import { useEventStream } from "@laravel/stream-react";23export default function Progress() {4 const { message } = useEventStream("/progress");56 return <div>{message}</div>;7}1import { useEventStream } from "@laravel/stream-react";23export default function Progress() {4 const { message } = useEventStream("/progress");56 return <div>{message}</div>;7}
When the stream runs out of events, Laravel sends a final update event containing </stream> so the @laravel/stream hooks know the stream has finished. If you consume the stream manually with the browser's EventSource API, close the connection when </stream> arrives so the browser doesn't reconnect automatically:
1const source = new EventSource("/progress");23source.addEventListener("update", (event) => {4 if (event.data === "</stream>") {5 source.close();67 return;8 }910 console.log(event.data);11});1const source = new EventSource("/progress");23source.addEventListener("update", (event) => {4 if (event.data === "</stream>") {5 source.close();67 return;8 }910 console.log(event.data);11});
You may customize the final event with end_with, or omit it with without_end_event:
1EventStream::new(events).end_with(Event::new("done", "complete"));23EventStream::new(events).without_end_event();1EventStream::new(events).end_with(Event::new("done", "complete"));23EventStream::new(events).without_end_event();
While no events arrive, Laravel sends a comment every 15 seconds so proxies don't close the connection.
Responses of your own
If several handlers in your application return the same kind of response, you may wrap it in a type of your own that implements IntoResponse. For example, an API that queues background work might define an Accepted type that serializes a payload as JSON with a 202 Accepted status:
1use laravel::prelude::*;23pub struct Accepted<T>(pub T);45impl<T: Serialize> IntoResponse for Accepted<T> {6 fn into_response(self) -> Response {7 (StatusCode::ACCEPTED, Json(self.0)).into_response()8 }9}1use laravel::prelude::*;23pub struct Accepted<T>(pub T);45impl<T: Serialize> IntoResponse for Accepted<T> {6 fn into_response(self) -> Response {7 (StatusCode::ACCEPTED, Json(self.0)).into_response()8 }9}
Handlers may now return Accepted(job) directly, and because Accepted implements IntoResponse, it also gains with_header, with_headers, with_cookie, and without_cookie.
Testing
To test the responses your routes return, send requests through the test Application and chain assertions onto the response. For example, these tests verify that /feed returns an RSS content type and that /dashboard redirects to /home/dashboard:
1use laravel::testing::prelude::*;23#[laravel::test]4async fn the_feed_is_rss(app: Application) {5 app.get("/feed")6 .await7 .assert_ok()8 .assert_header("content-type", "application/rss+xml");9}1011#[laravel::test]12async fn the_old_dashboard_redirects(app: Application) {13 app.get("/dashboard").await.assert_redirect_to("/home/dashboard");14}1use laravel::testing::prelude::*;23#[laravel::test]4async fn the_feed_is_rss(app: Application) {5 app.get("/feed")6 .await7 .assert_ok()8 .assert_header("content-type", "application/rss+xml");9}1011#[laravel::test]12async fn the_old_dashboard_redirects(app: Application) {13 app.get("/dashboard").await.assert_redirect_to("/home/dashboard");14}
To learn more about asserting status codes, headers, cookies, redirects, and JSON responses, check out the testing guide's section on available assertions. If you'd like to inspect the page a redirect leads to, check out following redirects.