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 Request type 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 the Request itself. Instead, you may describe the input you expect as a struct, and Laravel validates the input before your handler runs.
Accessing the request
Sometimes a handler needs more than a form's fields, such as a header, a cookie, or the request's URL. To get the current request in a handler, take a Request argument:
1use laravel::prelude::*;23pub async fn store(request: Request) -> laravel::Result<Redirect> {4 let locale = request.header("accept-language").unwrap_or("en");56 // Store the user...78 Ok(redirect!(users::index))9}1use laravel::prelude::*;23pub async fn store(request: Request) -> laravel::Result<Redirect> {4 let locale = request.header("accept-language").unwrap_or("en");56 // Store the user...78 Ok(redirect!(users::index))9}
Laravel reads the request's body before your handler runs, so JSON and form input are ready to use. Because it reads the body, a Request argument must be the handler's last argument. If your handler also takes route parameters or other arguments, put them before the request:
1use laravel::prelude::*;23pub async fn update(Params(id): Params<u64>, request: Request) -> laravel::Result<Redirect> {4 // Update the user with the given ID...56 Ok(redirect!(users::index))7}1use laravel::prelude::*;23pub async fn update(Params(id): Params<u64>, request: Request) -> laravel::Result<Redirect> {4 // Update the user with the given ID...56 Ok(redirect!(users::index))7}
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 request provides several methods for reading its path, URL, host, and method:
1use laravel::http::Method;23request.path(); // "/users/1"4request.url(); // "https://example.com/users/1", without the query string5request.full_url(); // "https://example.com/users/1?tab=posts"6request.origin(); // "https://example.com"7request.host(); // "example.com"8request.is_secure(); // Whether it was made over HTTPS9request.ip(); // The client's IP address, as an `IpAddr`, such as 203.0.113.51011if request.method() == Method::POST {12 // ...13}1use laravel::http::Method;23request.path(); // "/users/1"4request.url(); // "https://example.com/users/1", without the query string5request.full_url(); // "https://example.com/users/1?tab=posts"6request.origin(); // "https://example.com"7request.host(); // "example.com"8request.is_secure(); // Whether it was made over HTTPS9request.ip(); // The client's IP address, as an `IpAddr`, such as 203.0.113.51011if request.method() == Method::POST {12 // ...13}
To check whether the path matches a pattern, use resembles. A * matches any part of the path, so admin/* matches /admin/users and /admin/users/1:
1if request.resembles("admin/*") {2 // ...3}1if request.resembles("admin/*") {2 // ...3}
If your application runs behind a load balancer, ip, host, and is_secure 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 full_url_with_query to add or replace query parameters, and full_url_without_query to remove them. For example, on https://example.com/users?page=2:
1// "https://example.com/users?page=2&sort=name"2request.full_url_with_query([("sort", "name")]);3request.full_url_without_query(["page"]); // "https://example.com/users"1// "https://example.com/users?page=2&sort=name"2request.full_url_with_query([("sort", "name")]);3request.full_url_without_query(["page"]); // "https://example.com/users"
To learn more about reading a route parameter or checking which route matched the request, such as in a middleware, check out the routing guide's section on 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 header. It returns None when the client didn't send the header. If your API authenticates clients with tokens, bearer_token reads the token from an Authorization: Bearer header:
1let agent = request.header("user-agent"); // Option<&str>2let token = request.bearer_token(); // Option<&str>1let agent = request.header("user-agent"); // Option<&str>2let token = request.bearer_token(); // Option<&str>
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. For that, use headers, which returns the request's HeaderMap. You may loop over the map to read each header's name and value. A header's value may contain bytes that aren't text, so convert it with to_str, which fails for those values:
1for (name, value) in request.headers() {2 tracing::info!(3 header = %name,4 value = value.to_str().unwrap_or("(not text)"),5 "Webhook header",6 );7}1for (name, value) in request.headers() {2 tracing::info!(3 header = %name,4 value = value.to_str().unwrap_or("(not text)"),5 "Webhook header",6 );7}
The map may also hold several values for one header name, such as when a client sends an Accept header more than once. To read all of them, use get_all:
1for value in request.headers().get_all("accept") {2 // ...3}1for value in request.headers().get_all("accept") {2 // ...3}
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 accepts. For example, before you offer a CSV export of a report, you might check that the client can receive CSV:
1if request.accepts(&["text/csv"]) {2 // Offer the CSV export...3}1if request.accepts(&["text/csv"]) {2 // Offer the CSV export...3}
To respond in whichever format the client prefers, pass the types you offer to prefers. It follows the order and quality values in the client's Accept header, and returns None when the client accepts none of your types. For example, this handler serves a documentation page as Markdown to AI agents that ask for Markdown, and as HTML to browsers:
1use laravel::http::header;2use laravel::prelude::*;34pub async fn show(request: Request) -> Response {5 let markdown = "# Installation\n\nRun `cargo install laravel-rust-cli`.";67 match request.prefers(&["text/html", "text/markdown"]) {8 Some("text/markdown") => {9 ([(header::CONTENT_TYPE, "text/markdown")], markdown).into_response()10 }11 _ => view("docs.page", data! { markdown }).into_response(),12 }13}1use laravel::http::header;2use laravel::prelude::*;34pub async fn show(request: Request) -> Response {5 let markdown = "# Installation\n\nRun `cargo install laravel-rust-cli`.";67 match request.prefers(&["text/html", "text/markdown"]) {8 Some("text/markdown") => {9 ([(header::CONTENT_TYPE, "text/markdown")], markdown).into_response()10 }11 _ => view("docs.page", data! { markdown }).into_response(),12 }13}
If you only need to know whether the client wants JSON, use wants_json. It returns true when the type the client prefers most is JSON, such as for an API client that sends Accept: application/json. For example, this handler returns the posts as JSON to API clients, and as a page to everyone else:
1use laravel::prelude::*;23use crate::models::Post;45pub async fn index(request: Request) -> laravel::Result<Response> {6 let posts = Post::all().await?;78 if request.wants_json() {9 return Ok(Json(posts).into_response());10 }1112 Ok(view("posts.index", data! { posts }).into_response())13}1use laravel::prelude::*;23use crate::models::Post;45pub async fn index(request: Request) -> laravel::Result<Response> {6 let posts = Post::all().await?;78 if request.wants_json() {9 return Ok(Json(posts).into_response());10 }1112 Ok(view("posts.index", data! { posts }).into_response())13}
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 prefetch returns true for them. The user may never see a prefetched page, so skip side effects such as counting a page view:
1if !request.prefetch() {2 // Count the page view...3}1if !request.prefetch() {2 // Count the page view...3}
Cookies
To read a cookie the browser sent, such as the color theme a user picked, use cookie. On routes in the web group, Laravel encrypts your cookies, so cookie returns the decrypted value. If the browser changed the cookie's value, cookie returns None:
1let theme = request.cookie("theme"); // Option<String>1let theme = request.cookie("theme"); // Option<String>
To learn more about setting and deleting cookies, check out the cookies guide's section on sending cookies.
Input
Retrieving input
To read input from a submitted form or JSON request body, define a struct for the fields your handler expects. Defining a struct keeps your handler focused on the fields it asks for and prevents query string parameters from bleeding into form or JSON payloads. When those fields need validation rules such as a maximum length, use Valid<T>. When you don't need validation rules, mark the struct with #[laravel::input] and deserialize the body directly with parse:
1use laravel::prelude::*;23#[laravel::input]4pub struct NewUser {5 name: String,6 email: String,7 #[serde(default)]8 subscribe: bool,9}1011pub async fn store(request: Request) -> laravel::Result<Redirect> {12 let user: NewUser = request.parse()?;1314 // Store the user...1516 Ok(redirect!(users::index))17}1use laravel::prelude::*;23#[laravel::input]4pub struct NewUser {5 name: String,6 email: String,7 #[serde(default)]8 subscribe: bool,9}1011pub async fn store(request: Request) -> laravel::Result<Redirect> {12 let user: NewUser = request.parse()?;1314 // Store the user...1516 Ok(redirect!(users::index))17}
When reading HTML form submissions, parse automatically converts text fields into the types on your struct, such as turning age=42 into a u32 or a checked checkbox's "on" value into true. Because browsers omit unchecked checkboxes from form submissions, mark checkbox bool fields with #[serde(default)] so they default to false. For optional fields that may be omitted or null, wrap the field's type in Option.
Nested form fields deserialize into nested structs and lists, as JSON objects and arrays do. 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 list.
If the input doesn't fit your type, parse fails with an InvalidInput error, which names every wrong field with a message such as "The email field is required." Laravel responds to this error as it does to failed validation: it redirects a browser back to the form, and gives other clients a 422 response. These are the same English messages Laravel's validation rules use. If you'd like to change a message, or give a field a friendlier name, use Valid<T> instead. To learn more, check out the validation guide's section on custom messages and labels.
Laravel's default middleware trim whitespace from every input value except passwords, and turn empty strings into null. 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. Mark a struct with #[laravel::query] and take a Query<T> argument in your handler. It reads only the query string, ignoring any body the request has, and parses text into dates, enums, numbers, and other typed fields:
1use laravel::prelude::*;2use laravel::time::civil::Date;34#[derive(Serialize, Deserialize, Enum)]5#[serde(rename_all = "snake_case")]6pub enum Status {7 Active,8 Archived,9}1011#[laravel::query]12pub struct ProductFilters {13 #[default]14 q: String,15 #[default = 1]16 #[validate(min_value(1))]17 page: u32,18 status: Option<Status>,19 max_price: Option<f64>,20 since: Option<Date>,21}2223pub async fn index(Query(filters): Query<ProductFilters>) -> String {24 let max_price = filters.max_price.unwrap_or(100.0);2526 // List the products...2728 format!("Page {} for '{}' up to {max_price}", filters.page, filters.q)29}1use laravel::prelude::*;2use laravel::time::civil::Date;34#[derive(Serialize, Deserialize, Enum)]5#[serde(rename_all = "snake_case")]6pub enum Status {7 Active,8 Archived,9}1011#[laravel::query]12pub struct ProductFilters {13 #[default]14 q: String,15 #[default = 1]16 #[validate(min_value(1))]17 page: u32,18 status: Option<Status>,19 max_price: Option<f64>,20 since: Option<Date>,21}2223pub async fn index(Query(filters): Query<ProductFilters>) -> String {24 let max_price = filters.max_price.unwrap_or(100.0);2526 // List the products...2728 format!("Page {} for '{}' up to {max_price}", filters.page, filters.q)29}
#[laravel::query] is lenient for every field with a fallback (Option<T>, #[default], or #[default = value]). When a user submits a blank search form (?q=&page=) or opens a stale bookmark (?status=deleted&page=abc), Laravel drops the bad parameter and uses None or the field's default instead of failing the page. You may also attach #[validate(..)] rules, such as #[validate(min_value(1))] above, so ?page=0 falls back to 1.
A field without Option or #[default] is required, such as code: String on an OAuth callback. If a required parameter is missing, blank, or invalid, Laravel returns 400 Bad Request with an InvalidInput error. On a route in the web group, a browser receives an HTML error page rather than a redirect. Requests that expect JSON and all requests to routes in the api group receive a JSON response that lists each field's errors.
Because Query<T> doesn't read the request body, it may appear in any position in your handler's arguments, including before Valid<T> or Request. When your handler already takes Request, you may also call request.query::<ProductFilters>().await? directly.
The raw body and JSON
Valid<T> and request.parse() 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"}]. To deserialize the JSON body directly into a list or a single value, use request.json() instead:
1use laravel::prelude::*;23#[laravel::input]4pub struct Item {5 sku: String,6 quantity: u32,7}89pub async fn import(request: Request) -> laravel::Result<String> {10 let items: Vec<Item> = request.json()?;1112 // Import the items...1314 Ok(format!("Imported {} items", items.len()))15}1use laravel::prelude::*;23#[laravel::input]4pub struct Item {5 sku: String,6 quantity: u32,7}89pub async fn import(request: Request) -> laravel::Result<String> {10 let items: Vec<Item> = request.json()?;1112 // Import the items...1314 Ok(format!("Imported {} items", items.len()))15}
If the body isn't JSON, json fails with a 400 error. If the JSON doesn't fit your type, it fails with a 422 error that names the field, such as "The 1.sku field is required." for a second item with no sku.
Sometimes you need the exact bytes the client sent, such as to verify the signature on a webhook from Stripe. For that, use content. It returns the body exactly as the client sent it, before Laravel parses it or 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++. A request without a body gives you an empty value. For a multipart/form-data body, content returns None, because Laravel saves uploaded files to disk rather than keeping the body in memory:
1let payload = request.content().or_abort(400)?;2let signature = request.header("stripe-signature").or_abort(400)?;34// Verify the signature against the payload...1let payload = request.content().or_abort(400)?;2let signature = request.header("stripe-signature").or_abort(400)?;34// 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 templates usually read this old input with old. To learn more, check out the validation guide's section on displaying errors and old input.
If you'd like to read old input in a handler instead, call old on the request with the type you expect. It returns None when the field is absent, when its value isn't the type you asked for, or when the request has no session:
1let name: Option<String> = request.old("name");2let tags = request.old::<Vec<String>>("tags").unwrap_or_default();1let name: Option<String> = request.old("name");2let tags = request.old::<Vec<String>>("tags").unwrap_or_default();
To flash input yourself, such as after a check of your own fails, redirect back with the request's input:
1return Ok(Redirect::back().with_input(&request));1return Ok(Redirect::back().with_input(&request));
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. Receive each upload as an UploadedFile field on a validated struct alongside the form's other fields, and place the file's validation rules directly on that field:
1use laravel::http::UploadedFile;2use laravel::prelude::*;34#[laravel::input]5#[validate(authenticated)]6pub struct UpdateProfile {7 #[validate(required, max_length(255))]8 name: String,9 #[validate(image, max_kilobytes(2048))]10 avatar: Option<UploadedFile>,11}1213pub async fn update(Valid(form): Valid<UpdateProfile>) -> laravel::Result<Redirect> {14 if let Some(avatar) = form.avatar {15 // ...16 }1718 Ok(Redirect::back())19}1use laravel::http::UploadedFile;2use laravel::prelude::*;34#[laravel::input]5#[validate(authenticated)]6pub struct UpdateProfile {7 #[validate(required, max_length(255))]8 name: String,9 #[validate(image, max_kilobytes(2048))]10 avatar: Option<UploadedFile>,11}1213pub async fn update(Valid(form): Valid<UpdateProfile>) -> laravel::Result<Redirect> {14 if let Some(avatar) = form.avatar {15 // ...16 }1718 Ok(Redirect::back())19}
Use Option<UploadedFile> for a file the user may leave out. If the user doesn't choose a file before submitting the form, the field is None. For a multiple file input named photos[], use Vec<UploadedFile>, which holds the files in the order the user chose them.
By default, a form with uploads may be up to 16 MB, and may upload at most 20 files. If a route accepts larger files, give it a LimitUploads middleware of its own, such as .middleware(LimitUploads::megabytes(100)). 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.
File names, types, and extensions
An UploadedFile tells you about the file the user uploaded, such as its size and type:
1let name = avatar.client_name(); // "Taylor's photo.PNG"2let size = avatar.size(); // In bytes3let content_type = avatar.content_type(); // Some("image/png")4let extension = avatar.extension(); // Some("png")1let name = avatar.client_name(); // "Taylor's photo.PNG"2let size = avatar.size(); // In bytes3let content_type = avatar.content_type(); // Some("image/png")4let extension = avatar.extension(); // Some("png")
Laravel determines content_type and extension by reading the first few bytes of the file, not by trusting the name the user gave it. Most formats, such as PNG images and PDFs, begin with a recognizable signature. Text formats, such as CSV and plain text files, don't have one, so both methods return None for them. To accept a CSV upload, check its name with the extensions rule instead, as the validation guide's section on files shows.
client_name, client_extension, and client_content_type return what the user's browser claimed. Never trust them to decide what a file is, and never use the client name 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. For a small file, bytes reads the whole file into memory. For example, this handler reads each row of an uploaded CSV:
1use laravel::http::UploadedFile;2use laravel::prelude::*;34#[laravel::input]5#[validate(authenticated)]6pub struct ImportContacts {7 #[validate(required, extensions("csv"), max_kilobytes(1024))]8 contacts: UploadedFile,9}1011pub async fn import(Valid(form): Valid<ImportContacts>) -> laravel::Result<Redirect> {12 let bytes = form.contacts.bytes().await?;13 let contents = String::from_utf8_lossy(&bytes);1415 for row in contents.lines() {16 // Import the contact...17 }1819 Ok(Redirect::back())20}1use laravel::http::UploadedFile;2use laravel::prelude::*;34#[laravel::input]5#[validate(authenticated)]6pub struct ImportContacts {7 #[validate(required, extensions("csv"), max_kilobytes(1024))]8 contacts: UploadedFile,9}1011pub async fn import(Valid(form): Valid<ImportContacts>) -> laravel::Result<Redirect> {12 let bytes = form.contacts.bytes().await?;13 let contents = String::from_utf8_lossy(&bytes);1415 for row in contents.lines() {16 // Import the contact...17 }1819 Ok(Redirect::back())20}
For a large file, you may not want to load it all into memory at once. Laravel saves each upload to a temporary file, and path returns where that file is, so you may pass it to a library that reads the file itself, such as a CSV parser:
1let path = form.contacts.path(); // &Path1let path = form.contacts.path(); // &Path
Keeping uploaded files
Laravel saves each upload in a temporary directory, and deletes it once the request is done. To keep an upload, store it on one of your filesystem disks with store. Pass the directory to store the file in, and Laravel gives the file a unique, randomly generated name:
1let path = avatar.store("avatars").disk("public").await?;1let path = avatar.store("avatars").disk("public").await?;
store returns the file's path on the disk, which you may save in your database to find the file again later. If you leave out .disk(..), Laravel stores the file on your default disk.
If you'd like to choose the file's name yourself, use store_as and pass the name after the directory:
1let path = avatar.store_as("avatars", "profile.png").disk("public").await?;1let path = avatar.store_as("avatars", "profile.png").disk("public").await?;
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 fields or a JSON body as a type of your own, describe them in a struct marked with #[laravel::input], and take a Valid<T> argument in your handler. For example, this handler receives a new user's name and email address:
1use laravel::prelude::*;23#[laravel::input]4#[validate(anyone)]5pub struct NewUser {6 #[validate(required, max_length(100))]7 name: String,8 #[validate(required, email)]9 email: String,10}1112pub async fn store(Valid(user): Valid<NewUser>) -> Redirect {13 // Store the user...1415 redirect!(users::index)16}1use laravel::prelude::*;23#[laravel::input]4#[validate(anyone)]5pub struct NewUser {6 #[validate(required, max_length(100))]7 name: String,8 #[validate(required, email)]9 email: String,10}1112pub async fn store(Valid(user): Valid<NewUser>) -> Redirect {13 // Store the user...1415 redirect!(users::index)16}
Your handler only runs when the input fits the struct and passes its rules. Otherwise, Laravel redirects a browser back to the form with the errors and the input the user typed, and an API client gets a 422 JSON response that lists the errors. Valid<T> reads the request's body, so it must be the handler's last argument. To learn more about the rules you may use, check out the validation guide.
Input in middleware
Middleware receive a Request too. The request doesn't read its body until something asks for it, so a middleware won't see the fields of a form or JSON body at first. To read body input in a middleware, call load_input first and then deserialize the fields you need with parse. For example, this middleware logs the email address of every login attempt:
1use laravel::http::{Next, Request, Response, middleware};23#[laravel::input]4struct LoginAttempt {5 email: Option<String>,6}78#[middleware]9pub async fn log_login_attempts(10 mut request: Request,11 next: Next,12) -> laravel::Result<Response> {13 request.load_input().await?;1415 let attempt: LoginAttempt = request.parse()?;16 tracing::info!(email = attempt.email, "Login attempt");1718 Ok(next.run(request).await)19}1use laravel::http::{Next, Request, Response, middleware};23#[laravel::input]4struct LoginAttempt {5 email: Option<String>,6}78#[middleware]9pub async fn log_login_attempts(10 mut request: Request,11 next: Next,12) -> laravel::Result<Response> {13 request.load_input().await?;1415 let attempt: LoginAttempt = request.parse()?;16 tracing::info!(email = attempt.email, "Login attempt");1718 Ok(next.run(request).await)19}
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 transform_input. Laravel runs your transform on the query string and on the body's fields once the request reads them. Laravel's own TrimStrings and ConvertEmptyStringsToNull middleware work this way. For example, this middleware lowercases the email field:
1use laravel::http::{Next, Request, Response, middleware};2use serde_json::Value;34#[middleware]5pub async fn lowercase_emails(mut request: Request, next: Next) -> Response {6 request.transform_input(|input| {7 if let Some(Value::String(email)) = input.get_mut("email") {8 *email = email.to_lowercase();9 }10 });1112 next.run(request).await13}1use laravel::http::{Next, Request, Response, middleware};2use serde_json::Value;34#[middleware]5pub async fn lowercase_emails(mut request: Request, next: Next) -> Response {6 request.transform_input(|input| {7 if let Some(Value::String(email)) = input.get_mut("email") {8 *email = email.to_lowercase();9 }10 });1112 next.run(request).await13}
If you only need to lowercase or uppercase specific fields on an input or query struct, you may annotate 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.