跳至正文

Responses ​

Introduction ​

Every route and handler in your application returns an HTTP response to send back to the user's browser or API client. In Laravel, every handler returns a *web.Response, and the web package has a function for each kind of response, such as web.JSON, web.View, and web.Redirect.

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. Each function returns a response that you may keep changing before you return it, such as by setting its status code or attaching a header.

Creating responses ​

Text and JSON ​

The most basic response is plain text, which you return with web.Text:

go
package routes

import (
	"go.laravel.com/config"
	"go.laravel.com/routing"
	"go.laravel.com/web"
)

func Web(route *routing.Router, cfg *config.Config) {
	route.Get("/", func(r *web.Request) *web.Response {
		return web.Text("Hello World")
	})
}

When building an API or returning structured data, pass any value to web.JSON. Laravel encodes the value as JSON and sets the Content-Type header to application/json. Structs are encoded by their json tags:

go
package health

import "go.laravel.com/web"

type Health struct {
	Status  string `json:"status"`
	Version string `json:"version"`
}

func Show(r *web.Request) *web.Response {
	return web.JSON(Health{Status: "ok", Version: "1.0.0"})
}

For a small payload where defining a struct would add nothing, you may pass a map instead:

go
return web.JSON(map[string]any{"status": "ok", "version": "1.0.0"})

Since models are structs with json tags, you may also return a model or a slice of models:

go
package users

import (
	"go.laravel.com/model"
	"go.laravel.com/web"

	"app/models"
)

func Index(r *web.Request) *web.Response {
	users, err := model.Query[models.User]().Get(r)
	if err != nil {
		return web.Fail(err)
	}

	return web.JSON(users)
}

Any field tagged json:"-" is left out of the JSON. Your application's User model tags its Password and RememberToken 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 with web.View. Pass the view's name and the data it renders:

go
package pages

import "go.laravel.com/web"

func About(r *web.Request) *web.Response {
	return web.View("about", map[string]any{"Company": "Laravel"})
}

Sometimes you already have HTML that you trust, such as a terms of service page that your build step generates from Markdown. Pass it to web.HTML to send it as an HTML page. web.HTML sends the string exactly as you give it, without escaping it, so never put a value from your users in it. In this example, the generated terms.html sits beside the handler's file, and //go:embed builds it into your application:

go
package legal

import (
	_ "embed"

	"go.laravel.com/web"
)

//go:embed terms.html
var terms string

func Terms(r *web.Request) *web.Response {
	return web.HTML(terms)
}

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:

go
package posts

import (
	"go.laravel.com/inertia"
	"go.laravel.com/model"
	"go.laravel.com/web"

	"app/models"
)

func Show(r *web.Request) *web.Response {
	post, err := model.FromRoute[models.Post](r, "post")
	if err != nil {
		return web.Fail(err)
	}

	return inertia.Render("Posts/Show", inertia.Props{"post": post})
}

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 web.Created to encode a value as JSON with a 201 status, and web.NoContent to send an empty 204 response.

In this posts handler package, StorePost is the post's validated input, Store creates the post for the logged-in user, and Destroy deletes the post that the route names:

go
package posts

import (
	"go.laravel.com/model"
	"go.laravel.com/validation"
	"go.laravel.com/validation/rule"
	"go.laravel.com/web"

	"app/models"
)

type StorePost struct {
	Title string `json:"title"`
	Body  string `json:"body"`
}

func (f *StorePost) Rules() validation.Rules {
	return validation.For(f,
		rule.Field(&f.Title, rule.Required, rule.Max(255)),
		rule.Field(&f.Body, rule.Required),
	)
}

func Store(r *web.Request) *web.Response {
	form, err := r.Validate[StorePost]()
	if err != nil {
		return web.Fail(err)
	}

	post := models.Post{UserID: models.CurrentUser(r).ID, Title: form.Title, Body: &form.Body}
	if err := model.Create(r, &post); err != nil {
		return web.Fail(err)
	}

	return web.Created(post)
}

func Destroy(r *web.Request) *web.Response {
	post, err := model.FromRoute[models.Post](r, "post")
	if err != nil {
		return web.Fail(err)
	}

	if err := model.Delete(r, &post); err != nil {
		return web.Fail(err)
	}

	return web.NoContent()
}

If you'd also like to tell the client where the new post lives, attach a Location header with the post's URL. urls.Route builds the URL from the route's name and the post:

go
link, err := urls.Route(r, "posts.show", "post", &post)
if err != nil {
	return web.Fail(err)
}

return web.Created(post).WithHeader("Location", link)

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 the status code, chain WithStatus onto any response:

go
package exports

import (
	"net/http"

	"go.laravel.com/web"
)

func Store(r *web.Request) *web.Response {
	// Queue the export...

	return web.Text("Your export is being prepared.").WithStatus(http.StatusAccepted)
}

To attach a header to any response, chain WithHeader, once for each header. A header you attach replaces any existing header of the same name, including defaults such as a view's Content-Type:

go
func Feed(r *web.Request) *web.Response {
	return web.View("feed", nil).WithHeader("Content-Type", "application/rss+xml")
}

func Report(r *web.Request) *web.Response {
	return web.View("reports.show", nil).
		WithHeader("Cache-Control", "no-store").
		WithHeader("X-Frame-Options", "DENY")
}

If you'd like to add a second value to a header instead of replacing it, use the response's Header field, which is a standard http.Header, as in res.Header.Add("Link", next). To set caching headers on a whole route, use the CacheHeaders middleware.

Since every kind of response is a *web.Response, different branches of a handler may return different kinds of responses. For example, this handler answers an API client with JSON and a browser with a view:

go
func Show(r *web.Request) *web.Response {
	report := map[string]any{"title": "Q3 Sales", "total": 1200}

	if r.ExpectsJSON() {
		return web.JSON(report)
	}

	return web.View("reports.show", report)
}

To respond with an error status, return web.Abort with the status, or web.Fail with an error. Laravel renders the error as a page for browsers and as JSON for API clients, and sends any headers and cookies you chain onto the error response along with it:

go
return web.Abort(http.StatusServiceUnavailable).WithHeader("Retry-After", "60")

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 WithCookie, and remove a cookie from the browser with WithoutCookie. The cookie package builds the cookie, and cookie.Forever makes one that the browser keeps for as long as browsers allow:

go
package settings

import (
	"go.laravel.com/cookie"
	"go.laravel.com/web"
)

func UpdateTheme(r *web.Request) *web.Response {
	return web.Back().WithCookie(cookie.Forever("theme", "dark"))
}

func ForgetTheme(r *web.Request) *web.Response {
	return web.Back().WithoutCookie("theme")
}

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 web.Redirect. To send the user back to the page they came from, return web.Back:

go
func Dashboard(r *web.Request) *web.Response {
	return web.Redirect("/home/dashboard")
}

func Update(r *web.Request) *web.Response {
	// Save the user's settings...

	return web.Back()
}

You don't need to redirect back yourself when a submitted form is invalid. When you pass a validation error to web.Fail, Laravel redirects the user back to the form with the errors and their input. To learn more, check out the validation guide's section on validation responses.

Redirecting to routes ​

To redirect to one of your application's named routes, return web.RedirectRoute with the route's name. If you change the route's path later, the redirect follows it. Pass the route's parameters after the name, as names and values in pairs. For example, a handler that creates a post may redirect to the new post's page:

go
return web.RedirectRoute("posts.show", "post", &post)

Laravel fills the post parameter with the post's ID, or with its slug when the route names the slug, as in /posts/{post:slug}. To learn more, check out the URL generation guide's section on models and your own types.

To attach query parameters to a redirect, such as the active tab or a filter, chain WithQuery with a url.Values. To scroll the user to a specific section of the destination page, such as the comments section of a post, chain WithFragment. For example, this redirects to /posts/42?tab=comments#reply:

go
return web.RedirectRoute("posts.show", "post", &post).
	WithQuery(url.Values{"tab": {"comments"}}).
	WithFragment("reply")

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:

go
func Update(r *web.Request) *web.Response {
	// Update the user's profile...

	return web.Back().With("status", "Profile saved.")
}

The flashed value is available only for the next request. A view may read it with session "status". If your application uses Inertia, flash the value with inertia.Flash instead, so the next page receives it in its flash data.

If a check in your handler fails, such as an expired coupon, you may send the user back with an error next to that field. Chain WithError onto the redirect with the field name and message, and chain WithInput so the form can fill itself back in:

go
return web.Back().WithError("coupon", "That coupon has expired.").WithInput()

Chain additional WithError calls to attach errors to more fields, or pass a *web.InputError to WithErrors when redirecting after a failed form validation. Because flash data is stored in the session, With, WithInput, WithError, and WithErrors on redirects only work on routes in the web middleware group.

Redirecting to the intended page ​

When a guest visits a page that requires authentication, the Authenticate middleware stores the page's URL in the session and sends the guest to your login page. After they log in, auth.RedirectIntended sends them on to the page they originally requested. If the session holds no such page, it redirects to the path you pass it (or use auth.RedirectIntendedRoute to fall back to a named route):

go
package login

import (
	"go.laravel.com/auth"
	"go.laravel.com/web"
)

func Store(r *web.Request) *web.Response {
	// Log the user in...

	return auth.RedirectIntendedRoute("dashboard")
}

Redirect status codes ​

By default, redirects respond with a 302 Found status code. If you need a different status code, chain WithStatus onto the redirect, such as http.StatusSeeOther for a 303, or http.StatusMovedPermanently for a page that has moved for good:

go
return web.Redirect("/login").WithStatus(http.StatusSeeOther)

return web.Redirect("/pricing").WithStatus(http.StatusMovedPermanently)

If the old address needs no handler of its own, you may register a redirect route instead.

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.

File downloads ​

To prompt the user's browser to download a file, return web.Download with the file's path and the name the browser should save it under. Pass "" as the name to keep the file's own name:

go
func Report(r *web.Request) *web.Response {
	return web.Download("storage/reports/q3.pdf", "Q3 Report.pdf")
}

File responses ​

To display a file directly in the browser instead of downloading it, such as an image or a PDF, return web.File. For example, this handler shows the invoice whose ID the route names, as in /invoices/{invoice}:

go
package invoices

import (
	"fmt"

	"go.laravel.com/web"
)

func Show(r *web.Request) *web.Response {
	id, err := r.PathInt("invoice")
	if err != nil {
		return web.Fail(err)
	}

	return web.File(fmt.Sprintf("storage/invoices/%d.pdf", id))
}

For both web.Download and web.File, Laravel sets the Content-Type header from the file's extension and answers conditional and range requests, so browsers can cache the file and resume interrupted downloads. If the file doesn't exist, 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's path directly from untrusted user input, such as a raw filename from r.PathValue. A path containing .. or a leading / could allow a user to read any file your application can read. Use an integer ID, as r.PathInt returns, look up the path in your database, or serve the file from a storage disk instead.

If a file is stored without an extension, set its content type yourself with WithHeader:

go
return web.File(fmt.Sprintf("storage/avatars/%d", id)).WithHeader("Content-Type", "image/png")

If you generated a temporary file on disk only for this response, such as a one-off export, register a function with r.OnFinish that removes the file. Laravel calls the function once the response has been sent:

go
path := "storage/exports/tmp-users.csv"

// Write the export...

r.OnFinish(func() { os.Remove(path) })

return web.Download(path, "users.csv")

For a file on one of your storage disks, such as an S3 bucket, use web.DiskFile and web.DiskDownload. Both take the disk and the file's path on the disk, and storage.From returns your application's default disk:

go
return web.DiskDownload(storage.From(r), "invoices/2026-11.pdf", "invoice.pdf")

说明

Laravel serves the files in your public directory without a route. Use web.File and web.Download for private files that your handlers 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 web.Attachment with the file's name and any io.Reader, and Laravel sets the content type from the name:

go
package users

import (
	"encoding/csv"
	"strings"

	"go.laravel.com/model"
	"go.laravel.com/web"

	"app/models"
)

func Export(r *web.Request) *web.Response {
	users, err := model.Query[models.User]().Get(r)
	if err != nil {
		return web.Fail(err)
	}

	var export strings.Builder

	rows := csv.NewWriter(&export)
	rows.Write([]string{"name", "email"})
	for _, user := range users {
		rows.Write([]string{user.Name, user.Email})
	}
	rows.Flush()

	return web.Attachment("users.csv", strings.NewReader(export.String()))
}

web.Attachment sends the content as it reads it, so you may also pass on a download from another service without holding it in memory. For example, this handler sends an invoice PDF that a billing service returns. Laravel closes the billing service's response body once the download has been sent:

go
package invoices

import (
	"net/http"

	"go.laravel.com/httpclient"
	"go.laravel.com/web"
)

func Download(r *web.Request) *web.Response {
	invoice, err := httpclient.EnsureSuccessful().
		Stream(r, http.MethodGet, "https://billing.example.com/invoices/7.pdf")
	if err != nil {
		return web.Fail(err)
	}

	return web.Attachment("invoice.pdf", invoice.Body)
}

For a large export, holding the entire file in memory isn't practical. Instead, return a web.StreamDownload, which sends each row as your code writes it.

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 piece to the client as soon as your code writes it.

To stream a response, return web.Stream with a function that writes the body. Laravel calls the function once your handler returns, and sends each write to the client right away:

go
package deploys

import (
	"fmt"
	"io"

	"go.laravel.com/web"
)

func Deploy(r *web.Request) *web.Response {
	return web.Stream(func(w io.Writer) error {
		for _, step := range []string{"Building", "Migrating", "Done"} {
			// Run the step...

			if _, err := fmt.Fprintln(w, step); err != nil {
				return err
			}
		}

		return nil
	})
}

A write fails once the client disconnects, so returning the write's error stops your function. If your function returns any other error, Laravel reports the error and ends the response abruptly, so the client can tell the stream was cut short. By the time your function runs, Laravel has already sent the status and headers, so an error can't become an error page. Check what you can, such as whether the user may see the deployment, in the handler before you return the stream.

Streamed responses use text/plain by default. To send another content type, chain WithHeader onto the response:

go
func Answer(r *web.Request) *web.Response {
	return web.Stream(func(w io.Writer) error {
		_, err := io.WriteString(w, "# Summary\n\nHere is the streamed Markdown reply.")

		return err
	}).WithHeader("Content-Type", "text/markdown")
}

If you'd like the browser to save the stream as a file, return web.StreamDownload instead. It takes the file's name and the same kind of function, and sets the content type from the name. For example, this handler streams every post as a CSV row, reading the posts from the database 1,000 at a time with LazyByID:

go
package posts

import (
	"encoding/csv"
	"io"
	"strconv"

	"go.laravel.com/model"
	"go.laravel.com/web"

	"app/models"
)

func Export(r *web.Request) *web.Response {
	posts := model.Query[models.Post]().LazyByID(r, 1000)

	return web.StreamDownload("posts.csv", func(w io.Writer) error {
		rows := csv.NewWriter(w)
		for post, err := range posts {
			if err != nil {
				return err
			}
			if err := rows.Write([]string{strconv.FormatInt(post.ID, 10), post.Title}); err != nil {
				return err
			}
		}

		rows.Flush()

		return rows.Error()
	})
}

The route's timeout covers the handler but not the stream, so a stream may run for as long as it has something to send.

说明

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 stream, not inside the function that writes it.

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:

shell
npm install @laravel/stream-react

useStream sends a POST request, so register the route with route.Post in routes/web.go, 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:

tsx
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>
    );
}

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 web.StreamJSON, which encodes and sends each item as it arrives.

Pass web.StreamJSON an iterator, such as a model query's LazyByID, which reads the rows from the database in batches. Laravel sends the items as a JSON array:

go
package users

import (
	"go.laravel.com/model"
	"go.laravel.com/web"

	"app/models"
)

func Index(r *web.Request) *web.Response {
	return web.StreamJSON(model.Query[models.User]().LazyByID(r, 500)) // [{"id":1,...},...]
}

If you'd rather wrap the array in a JSON object under a top-level key, build a web.JSONStream with a Key and call its Response method:

go
return web.JSONStream[models.User]{
	Items: model.Query[models.User]().LazyByID(r, 500),
	Key:   "users",
}.Response() // {"users":[{"id":1,...},...]}

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.

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:

tsx
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>
    );
}

Event streams ​

When you want to push updates to a page as things happen on the server, such as a dashboard that shows how many posts there are as writers publish them, send server-sent events (text/event-stream) over one long-lived connection. Return web.StreamEvents with a function that calls send for each web.Event and returns any error. An event without a Name is sent as an update event. For example, this handler sends the number of posts every five seconds:

go
package posts

import (
	"time"

	"go.laravel.com/model"
	"go.laravel.com/web"

	"app/models"
)

func Count(r *web.Request) *web.Response {
	return web.StreamEvents(func(send func(web.Event) error) error {
		ticker := time.NewTicker(5 * time.Second)
		defer ticker.Stop()

		for {
			count, err := model.Query[models.Post]().Count(r)
			if err != nil {
				return err
			}
			if err := send(web.Event{Data: count}); err != nil {
				return err
			}

			select {
			case <-r.Done():
				return nil
			case <-ticker.C:
			}
		}
	})
}

send fails once the client disconnects, so returning its error stops the function cleanly. If your function returns any other error, Laravel reports it and ends the stream without sending the final </stream> event. Make the function stop when the request ends, as the example does with r.Done(), or it keeps running after the user leaves the page. If you already have an iter.Seq[web.Event] that can't fail, pass it to web.Events instead.

Laravel sends an event's Data as it is when the data is a string or a []byte, and as JSON otherwise. If you'd like to give an event a custom name that the browser can listen for separately, set its Name. To send HTML, such as a table row for each post as it's published, pass a web.Partial with a view's name and its data, and Laravel renders the view for the event:

go
if err := send(web.Event{
	Name: "post-published",
	Data: web.Partial{View: "posts.row", Data: post},
}); err != nil {
	return err
}

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:

tsx
import { useEventStream } from "@laravel/stream-react";

export default function PostCount() {
    const { message } = useEventStream("/posts/count");

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

When the iterator 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:

js
const source = new EventSource("/posts/count");

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

        return;
    }

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

If you'd like to send a different final event, or omit it altogether, build a web.EventStream and call its Response method:

go
return web.EventStream{
	Events: events,
	End:    &web.Event{Name: "done", Data: "complete"},
}.Response()

return web.EventStream{
	Events:          events,
	WithoutEndEvent: true,
}.Response()

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 give it a function of its own that returns a *web.Response. For example, an API that queues background work might define an Accepted function that encodes a payload as JSON with a 202 Accepted status:

go
package responses

import (
	"net/http"

	"go.laravel.com/web"
)

// Accepted answers a request whose work was queued.
func Accepted(value any) *web.Response {
	return web.JSON(value).WithStatus(http.StatusAccepted)
}

Handlers may now return responses.Accepted(job), and because it returns a *web.Response, they may chain WithHeader, WithCookie, and WithoutCookie onto it as they would onto any other response.

Testing ​

To test the responses your routes return, send requests with the test client and chain assertions onto each response. For example, these tests check that /feed returns an RSS content type and that saving the profile redirects back with a status message. From sets the page the request comes from, and AssertRedirectBack checks that the response redirected to that page:

go
package feature_test

import (
	"net/url"
	"testing"

	"app/tests"
)

func TestTheFeedIsRSS(t *testing.T) {
	tests.New(t).Get("/feed").
		AssertOK().
		AssertHeader("Content-Type", "application/rss+xml")
}

func TestSavingTheProfileRedirectsBack(t *testing.T) {
	tests.New(t).From("/profile").Post("/profile", url.Values{"name": {"Taylor"}}).
		AssertRedirectBack().
		AssertSessionHas("status", "Profile saved.")
}

The test client reads a streamed response to its end before it returns, so AssertSee checks the stream's whole body. 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.