Requests
- Introduction
- Accessing the request
- Request path, host, and method
- Request headers
- Content negotiation
- Cookies
- Input
- Files
- Typed, validated input
- Input in middleware
Introduction
Laravel's web.Request lets you work with the HTTP request your application is currently handling. Through it, you may read the request's URL, headers, and cookies, as well as the input and files the client submitted. For example, a sign-up form's handler might read the name and email address the user typed, and an API endpoint might read the JSON its client sent.
For most forms and API endpoints, you won't need to read fields one at a time. Instead, you may describe the input you expect as a struct, and Laravel fills the struct and validates the input for you.
Accessing the request
Every handler and middleware receives the current request as its first argument, so you read headers, cookies, route parameters, and input from r:
package users
import (
"go.laravel.com/web"
)
func Show(r *web.Request) *web.Response {
id := r.PathValue("user")
agent := r.Header.Get("User-Agent")
// ...
return web.Text(id + " (" + agent + ")")
}Laravel reads the request's body before your handler runs, so JSON and form input are ready to use. A web.Request embeds Go's *http.Request, so the fields and methods you know from net/http keep their usual names, such as r.Method, r.URL, r.Header, and r.PathValue. If a library takes a standard request, you may pass it r.Request.
The request is also a context.Context. When you run a query, call the cache, or call a function of your own that takes a ctx, pass r itself.
Request path, host, and method
Your handlers will often need to know where a request was sent. For example, you might highlight the current page in your navigation based on the request's path, or build a link from its full URL. The path and the method are fields of the standard request, and the request provides several methods for reading its URL and host:
import "net/http"
r.URL.Path // "/users/1"
r.FullURL() // "https://example.com/users/1?tab=posts"
r.Root() // "https://example.com"
r.Host // "example.com", with the port when the URL has one
r.Hostname() // "example.com", without the port
r.IsSecure() // Whether it was made over HTTPS
r.IP() // The client's IP address, such as "203.0.113.5"
if r.Method == http.MethodPost {
// ...
}To check whether the path matches a pattern, use r.Is. A * matches any part of the path, so admin/* matches /admin/users and /admin/users/1. If you pass several patterns, r.Is returns true when the path matches any of them:
if r.Is("admin/*") {
// ...
}If your application runs behind a load balancer, r.IP, r.Host, and r.IsSecure describe the load balancer's request to your application, not the client's original request. Once you trust the load balancer as a proxy, they describe the client's request instead.
Sometimes you'll want to link to the current page with a different query string, such as for sorting a list or moving between pages. Use r.FullURLWithQuery to add or replace query parameters, and r.FullURLWithoutQuery to remove them. For example, on https://example.com/users?page=2:
import "net/url"
r.FullURLWithQuery(url.Values{"sort": {"name"}}) // "https://example.com/users?page=2&sort=name"
r.FullURLWithoutQuery("page") // "https://example.com/users"To read a route parameter, such as the {user} in /users/{user}, use r.PathValue or r.PathInt. To learn more about route parameters, or about checking which route matched the request with r.RouteIs, check out the routing guide's sections on route parameters and accessing the current route.
Request headers
To read a header the client sent, such as the User-Agent of the browser that made the request, use the standard r.Header.Get. It returns "" when the client didn't send the header. If your API authenticates clients with tokens, r.BearerToken reads the token from an Authorization: Bearer header, and also returns "" when there is none:
agent := r.Header.Get("User-Agent")
token := r.BearerToken()Sometimes you'll need every header the client sent, such as to log what a webhook provider sends you while you set up its integration. r.Header is a standard http.Header, a map from each header's name to its values, so you may loop over it:
import "log/slog"
for name, values := range r.Header {
slog.InfoContext(r, "Webhook header.", "header", name, "values", values)
}A client may send several values for one header name, such as an Accept header sent more than once. r.Header.Get returns only the first value. To read all of them, use r.Header.Values:
for _, value := range r.Header.Values("Accept") {
// ...
}Content negotiation
Sometimes one URL serves several kinds of clients, such as a browser that wants an HTML page and a script that wants JSON. Each client lists the types of response it can handle in its Accept header, and the request offers a few methods for reading that list.
To check whether the client accepts a type at all, use r.Accepts. For example, before you offer a CSV export of a report, you might check that the client can receive CSV:
if r.Accepts("text/csv") {
// Offer the CSV export...
}To respond in whichever format the client prefers, pass the types you offer to r.Prefers. It follows the order and quality values in the client's Accept header, and returns "" when the client accepts none of your types. A request without an Accept header prefers the first type you list. For example, this handler serves a documentation page as Markdown to AI agents that ask for Markdown, and as HTML to browsers:
package docs
import "go.laravel.com/web"
func Show(r *web.Request) *web.Response {
markdown := "# Installation\n\nRun `laravel new example-app`."
if r.Prefers("text/html", "text/markdown") == "text/markdown" {
return web.Text(markdown).WithHeader("Content-Type", "text/markdown")
}
return web.View("docs.page", map[string]any{"markdown": markdown})
}If you only need to know whether to answer with JSON, use r.ExpectsJSON. It returns true for every request to a route in routes/api.go, even when an API client such as curl sends no Accept header, and for any request whose Accept header prefers JSON. Laravel makes the same check when it decides whether to render an error as JSON, so use ExpectsJSON for a handler that you register in both routes/web.go and routes/api.go. For example, this handler returns the posts as JSON to API clients, and as a page to everyone else:
package posts
import (
"go.laravel.com/model"
"go.laravel.com/web"
"app/models"
)
func Index(r *web.Request) *web.Response {
posts, err := model.Query[models.Post]().Get(r)
if err != nil {
return web.Fail(err)
}
if r.ExpectsJSON() {
return web.JSON(posts)
}
return web.View("posts.index", posts)
}Browsers and some frontend libraries, including Inertia, can load a page before the user clicks a link to it, so the page appears instantly when they do. These requests carry a Sec-Purpose: prefetch or Purpose: prefetch header, and r.IsPrefetch returns true for them. The user may never see a prefetched page, so skip side effects such as counting a page view:
if !r.IsPrefetch() {
// Count the page view...
}Cookies
To read a cookie's value, such as the color theme a user picked, use r.CookieValue. It returns "" when the browser didn't send the cookie, so you may pair it with cmp.Or for a default:
theme := cmp.Or(r.CookieValue("theme"), "light")To inspect the *http.Cookie itself or tell an empty cookie from a missing one, use r.Cookie, which returns http.ErrNoCookie when the browser didn't send the cookie:
if c, err := r.Cookie("theme"); err == nil {
// ...
}On routes in the web middleware group, Laravel encrypts your cookies, so r.CookieValue and c.Value hold the decrypted value. If the browser changed the cookie's value, r.CookieValue returns "" and r.Cookie returns http.ErrNoCookie as if the browser hadn't sent it. To learn more about setting and deleting cookies, check out the cookies guide's section on sending cookies.
Input
Retrieving input
A request's body input comes from a JSON object, a URL-encoded form, or a multipart/form-data body. You read body input by defining a struct with json tags for the fields you expect, so your handler only sees what it asks for and query string parameters can't bleed into form or JSON bodies. When those fields need validation rules such as a maximum length, use r.Validate. When you don't need validation rules, decode the body directly with r.Bind:
package users
import "go.laravel.com/web"
type newUser struct {
Name string `json:"name"`
Email string `json:"email"`
Roles []string `json:"roles"`
Subscribe bool `json:"subscribe"`
}
func Store(r *web.Request) *web.Response {
input, err := r.Bind[newUser]()
if err != nil {
return web.Fail(err)
}
// Store the user...
return web.RedirectRoute("users.index")
}r.Bind reads form text as whatever type the field asks for. For example, age=42 fills an int, and a checked checkbox's on fills a bool with true. Nested form fields fill nested structs and slices, so address[city] fills the City field of an Address struct, and items[0][sku] fills the SKU of the first item in an Items slice. If the request doesn't send a field, the struct's field keeps its zero value. If you need to bind into an already-populated struct, call r.BindInto(&input).
If a value doesn't fit the field's type, such as age=abc, r.Bind returns an invalid input error that names every wrong field with a message such as "The age field must be an integer." Pass the error to web.Fail as it is, and Laravel responds as it does to failed validation: it redirects a browser back to the form, and gives other clients a 422 response. To change a message or give a field a friendlier name, use r.Validate instead.
Laravel's default middleware trim whitespace from every string of input except passwords, and turn empty strings into nil, so a field the user left blank reads as missing. They do this for the query string and the body alike. To learn more about turning either one off or exempting a field, check out the middleware guide's section on customizing the defaults.
Query string input
A search or listing page usually reads its filters from the query string, such as /products?status=archived&max_price=50. Describe the parameters as a struct with json tags and call r.Query or r.QueryInto. They read only the query string, ignoring any body the request has, and parse text into dates, numbers, slices, and other typed fields:
package products
import (
"fmt"
"go.laravel.com/date"
"go.laravel.com/validation"
"go.laravel.com/validation/rule"
"go.laravel.com/web"
)
type ProductFilters struct {
Q string `json:"q"`
Page int `json:"page"`
Status string `json:"status"`
MaxPrice *float64 `json:"max_price"`
Since *date.Date `json:"since"`
}
func (f *ProductFilters) Rules() validation.Rules {
return validation.For(f,
rule.Field(&f.Page, rule.Min(1)),
rule.Field(&f.Status, rule.In("active", "archived")),
)
}
func Index(r *web.Request) *web.Response {
filters := ProductFilters{Page: 1}
if err := r.QueryInto(&filters); err != nil {
return web.Fail(err)
}
// List the products...
return web.Text(fmt.Sprintf("Page %d for %q", filters.Page, filters.Q))
}r.Query and r.QueryInto are lenient for optional fields. When a visitor submits a blank search form (?q=&page=) or opens a stale bookmark (?status=deleted&page=abc&page=0), Laravel drops the bad parameter and keeps the field's zero value (or its starting value in r.QueryInto, such as Page: 1 above) instead of failing the page.
When a query parameter is required (such as code and state on an OAuth callback), add rule.Required in Rules(). If a required parameter is missing, blank, or invalid, r.Query returns a 400 Bad Request error wrapping *web.InputError: API clients receive a 400 JSON response listing each field's errors, and browsers receive a 400 error page rather than a redirect:
type OAuthCallback struct {
Code string `json:"code"`
State string `json:"state"`
}
func (f *OAuthCallback) Rules() validation.Rules {
return validation.For(f,
rule.Field(&f.Code, rule.Required),
rule.Field(&f.State, rule.Required),
)
}
func Callback(r *web.Request) *web.Response {
params, err := r.Query[OAuthCallback]()
if err != nil {
return web.Fail(err)
}
// Exchange params.Code and verify params.State...
return web.Redirect("/")
}The raw body and JSON
r.Validate and r.Bind only read named fields, so they can't read a JSON body whose top level is an array or a single value, such as [{"sku": "A-1", "quantity": 2}]. To decode the JSON body directly into any type, call r.JSON[T](), which returns a 400 error for empty or malformed JSON and leaves r.Body readable again (use r.JSONInto(&dst) to decode into an existing value):
package orders
import (
"fmt"
"go.laravel.com/web"
)
type item struct {
SKU string `json:"sku"`
Quantity int `json:"quantity"`
}
func Import(r *web.Request) *web.Response {
items, err := r.JSON[[]item]()
if err != nil {
return web.Fail(err)
}
// Import the items...
return web.Text(fmt.Sprintf("Imported %d items", len(items)))
}Sometimes you need the exact bytes the client sent, such as to verify the signature on a webhook from Stripe. Laravel reads a form or JSON body before your handler runs, but leaves the body's bytes in place, so you may read r.Body as you would in any Go program. It holds the body exactly as the client sent it, before Laravel trims any whitespace. For a JSON body, that's the JSON text, such as {"name":" Taylor "}. For a URL-encoded form, it's the encoded text, such as name=++Taylor++. For a multipart/form-data body, r.Body is empty, because Laravel saves uploaded files to disk as it reads the body rather than keeping the body in memory:
import "io"
payload, err := io.ReadAll(r.Body)
if err != nil {
return web.Fail(err)
}
signature := r.Header.Get("Stripe-Signature")
// Verify the signature against the payload...Old input
When a form fails validation, Laravel flashes the form's input to the session, so you can fill the form back in with what the user typed. Your views usually read this old input with old. To learn more, check out the templates guide's section on validation errors and old input.
If you'd like to read old input in a handler instead, use the session's OldInput method. It returns the field's value and whether the old input had the field:
email, ok := r.Session().OldInput("email")To flash input yourself, such as after a check of your own fails, redirect back with the request's input. Laravel never keeps the password, password_confirmation, and current_password fields in old input:
return web.Back().WithInput()说明
If your application uses Inertia, you don't need old input. Inertia forms keep the user's input in the browser.
Files
Retrieving uploaded files
When a user uploads an avatar or attaches photos to a post, the files arrive in a multipart/form-data body, so the form needs enctype="multipart/form-data". Declare each upload as a *web.Upload field (or []*web.Upload for a multi-file input such as <input type="file" name="photos[]" multiple>) on your input struct and read it with r.Validate or r.Bind. A *web.Upload field is nil when the user didn't choose a file:
package avatars
import "go.laravel.com/web"
type UpdateAvatar struct {
Avatar *web.Upload `json:"avatar"`
Photos []*web.Upload `json:"photos"`
}
func Update(r *web.Request) *web.Response {
form, err := r.Bind[UpdateAvatar]()
if err != nil {
return web.Fail(err)
}
if form.Avatar != nil {
// ...
}
for _, photo := range form.Photos {
// ...
}
return web.Back()
}To check a file's type and size before you use it, add file rules in Rules() and call r.Validate. To learn more, check out the validation guide's section on validating files.
By default, a form with uploads may be up to 16 MiB, and may upload at most 20 files. If a route accepts larger files, raise its limit with Limits, such as .Limits(web.Limits{Uploads: 100 << 20}) for 100 MiB. To allow more files, set the SERVER_MAX_FILE_UPLOADS environment variable. A form over either limit gets a 413 response before your handler runs. To learn more, check out the routing guide's section on request limits.
File names, types, and extensions
A *web.Upload tells you about the file the user uploaded, such as its size and type:
avatar.Name // "Taylor's photo.PNG"
avatar.Size // In bytes
avatar.ContentType() // "image/png"
avatar.Extension() // "png"Laravel determines ContentType and Extension by reading the file's own bytes, not by trusting the name the user gave it. So decide what to accept from ContentType. When Laravel can't recognize a file's type, ContentType returns application/octet-stream and Extension returns "".
警告
Name is the name the user's browser sent, with any directory removed. Never trust it to decide what a file is, and never use it as a path.
Sometimes you'll want to read an uploaded file's contents yourself, such as to import the contacts in a CSV file. Laravel saves each upload to a temporary file, and Open opens that file for reading. For example, this handler reads an uploaded CSV file one row at a time, so even a large file never sits in memory all at once, and adds each row to a contacts table:
package contacts
import (
"encoding/csv"
"errors"
"io"
"net/http"
"go.laravel.com/db"
"go.laravel.com/web"
)
func Import(r *web.Request) *web.Response {
var form struct {
Contacts *web.Upload `json:"contacts"`
}
if err := r.BindInto(&form); err != nil {
return web.Fail(err)
}
if form.Contacts == nil {
return web.Abortf(http.StatusUnprocessableEntity, "Choose a CSV file to import.")
}
file, err := form.Contacts.Open()
if err != nil {
return web.Fail(err)
}
defer file.Close()
rows := csv.NewReader(file)
rows.FieldsPerRecord = 2
for {
row, err := rows.Read()
if errors.Is(err, io.EOF) {
break
}
if err != nil {
return web.Abortf(
http.StatusUnprocessableEntity,
"Each row needs a name and an email address.",
)
}
contact := db.Values{"name": row[0], "email": row[1]}
if err := db.Table("contacts").Insert(r, contact); err != nil {
return web.Fail(err)
}
}
return web.Back()
}If a library reads the file itself, such as an image processor that takes a file name, pass it Path, which returns where the temporary file is:
path := upload.Path()Keeping uploaded files
Laravel saves each upload in a temporary file, and deletes it once the response has been sent. To keep an upload, store it on one of your storage disks with Store before your handler returns. Pass the request, the disk, and the directory to store the file in, and Laravel gives the file a unique, randomly generated name with the right extension:
import "go.laravel.com/storage"
path, err := avatar.Store(r, storage.Use("public"), "avatars")Store returns the file's path on the disk, which you may save in your database to find the file again later.
If you'd like to choose the file's name yourself, use StoreAs and pass the name after the directory:
path, err := avatar.StoreAs(r, storage.Use("public"), "avatars", "profile.png")To learn more about storing uploads, such as validating an upload first, check out the file storage guide's section on file uploads.
Typed, validated input
To receive a form's input as a type of your own, describe the fields in a struct with json tags, give the struct a Rules method, and call r.Validate in your handler. For example, this handler receives a new user's name and email address:
package users
import (
"go.laravel.com/validation"
"go.laravel.com/validation/rule"
"go.laravel.com/web"
)
type NewUser struct {
Name string `json:"name"`
Email string `json:"email"`
}
func (f *NewUser) Rules() validation.Rules {
return validation.For(f,
rule.Field(&f.Name, rule.Required, rule.Max(100)),
rule.Field(&f.Email, rule.Required, rule.Email),
)
}
func Store(r *web.Request) *web.Response {
user, err := r.Validate[NewUser]()
if err != nil {
return web.Fail(err)
}
// Store the user...
return web.RedirectRoute("users.index")
}When the input passes its rules, Validate fills the struct and your handler carries on. Otherwise, pass the error to web.Fail as it is. Laravel redirects a browser back to the form with the errors and the input the user typed, and gives an API client a 422 JSON response that lists the errors. To learn more about the rules you may use, check out the validation guide.
Input in middleware
Middleware receive the request too, and read input with the same methods as handlers. The first call to r.Bind or r.Validate reads the body, so a route middleware sees the fields of a form or JSON body as a handler does. For example, this middleware logs the email address of every login attempt:
package auth
import (
"log/slog"
"go.laravel.com/web"
)
type LogLoginAttempts struct{}
func (LogLoginAttempts) Handle(r *web.Request, next web.Next) *web.Response {
var form struct {
Email string `json:"email"`
}
if err := r.BindInto(&form); err == nil && form.Email != "" {
slog.InfoContext(r, "Login attempt.", "email", form.Email)
}
return next(r)
}Read body input only in middleware you attach to routes or groups. A global middleware runs before Laravel applies the route's request limits, so reading body input there would hold every route to the default limits. To normalize input in a global middleware without forcing the body to load, use r.Transform.
Transforming input
Sometimes a middleware should change a field whenever it's read across every route, without forcing the body to load. For that, use r.Transform. Laravel calls your function with each value's "dot" notation key and the value, and uses the value your function returns. It runs your function on the input the request has so far, and again on the body's fields once the request reads them. Laravel's own TrimStrings and ConvertEmptyStrings middleware work this way. For example, this middleware lowercases the email field:
package input
import (
"strings"
"go.laravel.com/web"
)
type LowercaseEmails struct{}
func (LowercaseEmails) Handle(r *web.Request, next web.Next) *web.Response {
r.Transform(func(key string, value any) any {
if email, ok := value.(string); ok && key == "email" {
return strings.ToLower(email)
}
return value
})
return next(r)
}If you only need to lowercase or uppercase specific fields on an input struct, you may tag those fields directly with transform:"lowercase" or transform:"uppercase" instead of writing a middleware. To learn more, check out the validation guide's section on transforming input fields.