Routing
- Basic routing
- Route parameters
- Linking to routes
- Route groups
- Resource routes
- Fallback routes
- Form method spoofing
- Accessing the current route
- CORS
- The health route
Basic routing
When someone visits a page in your application or submits a form, Laravel looks at the request's method and URI, such as GET /greeting, and finds the route that matches it. The route tells Laravel which code should handle the request. The simplest route pairs a URI with a closure that returns the response:
1use laravel::prelude::*;23pub fn routes(route: &mut Router) {4 route.get("/greeting", async || "Hello World");5}1use laravel::prelude::*;23pub fn routes(route: &mut Router) {4 route.get("/greeting", async || "Hello World");5}
A closure may also ask for what it needs through its arguments, and Laravel provides them when the request comes in. For example, a closure that takes a User receives the user whose ID is in the URI, so a request to /users/1 returns the name of user 1. If no user has that ID, Laravel responds with a 404 page instead:
1use crate::models::User;23pub fn routes(route: &mut Router) {4 route.get("/users/{user}", async |user: User| user.name);5}1use crate::models::User;23pub fn routes(route: &mut Router) {4 route.get("/users/{user}", async |user: User| user.name);5}
Closures are handy for a quick page, but as your application grows, a route file full of them gets hard to read, since every page's logic sits in one place. So most routes point at a handler instead: an async function in its own module under src/http/handlers. The route file stays a short list of URIs, and each handler holds the code for one page. A handler's arguments are extractors, such as the request, a service, or route parameters, and it returns a response:
1use crate::http::handlers::users;23pub fn routes(route: &mut Router) {4 route.get("/users", users::index);5 route.get("/users/{user}", users::show);6 route.post("/users", users::store);7}1use crate::http::handlers::users;23pub fn routes(route: &mut Router) {4 route.get("/users", users::index);5 route.get("/users/{user}", users::show);6 route.post("/users", users::store);7}
The default route files
A route file is a function that receives a Router. Your application keeps its route files in src/routes and registers them in src/app.rs:
1Application::configure()2 .with_routing(|routing, _| {3 routing4 .web(routes::web::routes)5 .api(routes::api::routes);6 })1Application::configure()2 .with_routing(|routing, _| {3 routing4 .web(routes::web::routes)5 .api(routes::api::routes);6 })
For most applications, you'll start by defining routes in src/routes/web.rs. Routes registered with web run within the web middleware group, which provides sessions, encrypted cookies, and CSRF protection.
If other applications, scripts, or services will call your application's API, define those routes in src/routes/api.rs. Routes registered with api are stateless and run within the api middleware group. Laravel adds /api to the start of every URI in src/routes/api.rs, so a /users route defined in that file responds to /api/users. You may change the prefix with api_prefix:
1routing.api(routes::api::routes).api_prefix("/api/v1");1routing.api(routes::api::routes).api_prefix("/api/v1");
To register a route file that runs neither group, use routes. Its routes get no session, no CSRF check, and no prefix, so you choose their middleware yourself:
1// src/app.rs2.with_routing(|routing, _| {3 routing4 .web(routes::web::routes)5 .api(routes::api::routes)6 .routes(routes::webhooks::routes);7})1// src/app.rs2.with_routing(|routing, _| {3 routing4 .web(routes::web::routes)5 .api(routes::api::routes)6 .routes(routes::webhooks::routes);7})
1// src/routes/webhooks.rs2use laravel::prelude::*;34use crate::http::handlers::webhooks;5use crate::http::middleware::verify_stripe_signature;67pub fn routes(route: &mut Router) {8 route.middleware(verify_stripe_signature).group(|route| {9 route.post("/webhooks/stripe", webhooks::stripe);10 });11}1// src/routes/webhooks.rs2use laravel::prelude::*;34use crate::http::handlers::webhooks;5use crate::http::middleware::verify_stripe_signature;67pub fn routes(route: &mut Router) {8 route.middleware(verify_stripe_signature).group(|route| {9 route.post("/webhooks/stripe", webhooks::stripe);10 });11}
You may call web, api, and routes more than once, to split your routes across several files.
The closure's second argument is your application's configuration, so you may register some routes only in some environments:
1.with_routing(|routing, config| {2 routing.web(routes::web::routes);34 if config.app.debug {5 routing.web(routes::debug::routes);6 }7})1.with_routing(|routing, config| {2 routing.web(routes::web::routes);34 if config.app.debug {5 routing.web(routes::debug::routes);6 }7})
Available router methods
The router has a method for each HTTP verb:
1route.get(uri, handler);2route.post(uri, handler);3route.put(uri, handler);4route.patch(uri, handler);5route.delete(uri, handler);6route.options(uri, handler);1route.get(uri, handler);2route.post(uri, handler);3route.put(uri, handler);4route.patch(uri, handler);5route.delete(uri, handler);6route.options(uri, handler);
A GET route also responds to HEAD. To respond to several methods, use on. To respond to every method, use any:
1use laravel::http::Method;23route.on(&[Method::GET, Method::POST], "/search", search::show);4route.any("/webhooks/stripe", webhooks::stripe);1use laravel::http::Method;23route.on(&[Method::GET, Method::POST], "/search", search::show);4route.any("/webhooks/stripe", webhooks::stripe);
Redirect routes
A route that only redirects to another URI doesn't need a handler. Use redirect for a 302, or permanent_redirect for a 301:
1route.redirect("/here", "/there");2route.permanent_redirect("/here", "/there");1route.redirect("/here", "/there");2route.permanent_redirect("/here", "/there");
Redirects are especially handy when you rename part of your site. Say your blog's posts moved from /posts to /articles. Visitors and search engines still have the old links, so redirect them to the new ones. The destination may use the same parameters as the old URI:
1route.permanent_redirect("/posts/{post}", "/articles/{post}");2route.permanent_redirect("/blog/{*slug}", "https://blog.example.com/{*slug}");1route.permanent_redirect("/posts/{post}", "/articles/{post}");2route.permanent_redirect("/blog/{*slug}", "https://blog.example.com/{*slug}");
The second redirect uses a wildcard parameter, {*slug}, which captures the rest of the path, slashes and all. So /blog/2026/hello-world redirects to https://blog.example.com/2026/hello-world, which is handy when you move a whole section of your site to another domain.
View and Inertia routes
Some pages have no logic behind them, such as an about page or a pricing page whose content lives entirely in its template. Writing a handler that only renders the page would add a function with nothing in it, so the route may render a view or an Inertia page itself. Use view with the view's name, or inertia with the name of the page component:
1route.view("/about", "about");2route.inertia("/pricing", "Pricing");1route.view("/about", "about");2route.inertia("/pricing", "Pricing");
The view receives only the data shared with every view, and the page only your shared props. For more data, write a handler. These routes and redirect routes have no handler to link to, so link to them by their URI.
Listing your routes
The route:list console command gives you an overview of every route your application defines:
1laravel route:list1laravel route:list
You may also add a few options to the command. -v shows each route's middleware, and --json prints the list as JSON for scripts and other tools. To see only some of your routes, filter the list by URI with --path=admin, or by handler with --handler=users.
Route parameters
To capture a segment of the URI, such as a user's ID, define a route parameter in braces:
1route.get("/users/{user}", users::show);2route.get("/posts/{post}/comments/{comment}", comments::show);1route.get("/users/{user}", users::show);2route.get("/posts/{post}/comments/{comment}", comments::show);
Handlers receive parameters with the Params extractor, which parses each one into the type you give it, such as u64 or String. Several parameters arrive as a tuple, in the order the URI names them:
1use laravel::prelude::*;23pub async fn show(Params(id): Params<u64>) -> String {4 format!("User {id}")5}67pub async fn show_comment(Params((post, comment)): Params<(u64, u64)>) -> String {8 format!("Comment {comment} on post {post}")9}1use laravel::prelude::*;23pub async fn show(Params(id): Params<u64>) -> String {4 format!("User {id}")5}67pub async fn show_comment(Params((post, comment)): Params<(u64, u64)>) -> String {8 format!("Comment {comment} on post {post}")9}
If a parameter doesn't parse into its type, such as /users/taylor for a u64, the request gets a 404 and your handler never runs.
A wildcard parameter, written as {*path}, captures the rest of the URI, including its slashes:
1route.get("/files/{*path}", files::show);1route.get("/files/{*path}", files::show);
When several routes match a URI, Laravel compares them one segment at a time. A fixed segment such as create beats a parameter such as {user}, and a parameter beats a wildcard such as {*path}. So /users/create reaches a /users/create route even if you registered /users/{user} first.
Optional parameters
Add ? to a parameter's name to make its segment optional. Optional parameters must come at the end of the URI:
1route.get("/archive/{year?}/{month?}", archive::show);1route.get("/archive/{year?}/{month?}", archive::show);
This route matches /archive, /archive/2026, and /archive/2026/10. Give each optional parameter an Option type, and choose defaults in your handler. This handler receives the parameters in a struct, which keeps them named and organized, so params.year can't be mixed up with params.month:
1use laravel::prelude::*;23#[derive(Deserialize)]4pub struct ArchiveParams {5 year: Option<u16>,6 month: Option<u8>,7}89pub async fn show(Params(params): Params<ArchiveParams>) -> String {10 match params.year {11 Some(year) => format!("Archive for {year}, month {:?}", params.month),12 None => "All archives".to_owned(),13 }14}1use laravel::prelude::*;23#[derive(Deserialize)]4pub struct ArchiveParams {5 year: Option<u16>,6 month: Option<u8>,7}89pub async fn show(Params(params): Params<ArchiveParams>) -> String {10 match params.year {11 Some(year) => format!("Archive for {year}, month {:?}", params.month),12 None => "All archives".to_owned(),13 }14}
A tuple works too, and is shorter when you have one or two parameters. For example, Params<(u16, Option<u8>)> fits /archive/{year}/{month?}.
Restricting parameter values
A parameter that doesn't parse into its type is a 404, so the type you choose is also the parameter's constraint. To accept only a fixed set of values, such as the categories of a store, receive the parameter as an enum:
1use laravel::prelude::*;23#[derive(Deserialize)]4#[serde(rename_all = "lowercase")]5pub enum Category {6 Movies,7 Songs,8 Paintings,9}1011pub async fn show(Params(category): Params<Category>) -> &'static str {12 match category {13 Category::Movies => "Movies",14 Category::Songs => "Songs",15 Category::Paintings => "Paintings",16 }17}1use laravel::prelude::*;23#[derive(Deserialize)]4#[serde(rename_all = "lowercase")]5pub enum Category {6 Movies,7 Songs,8 Paintings,9}1011pub async fn show(Params(category): Params<Category>) -> &'static str {12 match category {13 Category::Movies => "Movies",14 Category::Songs => "Songs",15 Category::Paintings => "Paintings",16 }17}
With this handler on /categories/{category}, /categories/songs reaches the handler and /categories/podcasts is a 404.
Models in route parameters
When a parameter holds a model's key, such as the post's ID in /posts/{post}, take the model as a handler argument. Before your handler runs, Laravel automatically retrieves the post with that ID from your database and passes it in. If no post has that ID, Laravel responds with a 404, and your handler never runs:
1use crate::models::Post;23pub async fn show(post: Post) -> String {4 post.title5}1use crate::models::Post;23pub async fn show(post: Post) -> String {4 post.title5}
To find the post by another field, such as its slug, name the field after a colon, as in /blog/{post:slug}. To learn more about finding models by something other than their ID, check out the models guide's section on customizing the key.
To find a model outside a handler's arguments, such as in middleware, call request.model with the parameter's name:
1let post: Post = request.model("post").await?;1let post: Post = request.model("post").await?;
A handler may take a model and other route parameters together. Take the model as its own argument, and the other parameters with Params. A struct works best here, because it only names the parameters you want and leaves out the model's. For example, for a route on /posts/{post}/comments/{sort}:
1use laravel::prelude::*;23use crate::models::Post;45#[derive(Deserialize)]6pub struct CommentParams {7 sort: String,8}910pub async fn index(post: Post, Params(params): Params<CommentParams>) -> String {11 format!("Comments on {}, sorted by {}", post.title, params.sort)12}1use laravel::prelude::*;23use crate::models::Post;45#[derive(Deserialize)]6pub struct CommentParams {7 sort: String,8}910pub async fn index(post: Post, Params(params): Params<CommentParams>) -> String {11 format!("Comments on {}, sorted by {}", post.title, params.sort)12}
Linking to routes
You link to a route by its handler, the function you registered it with. In a handler or middleware, pass the handler and any parameters to route! or redirect! (both are in the prelude):
1let url = route!(users::show, 1)?; // http://localhost/users/123let response = redirect!(users::show, 1);1let url = route!(users::show, 1)?; // http://localhost/users/123let response = redirect!(users::show, 1);
You may pass a model in place of its ID. Laravel fills the parameter with the model's route key, which is its ID unless you've customized the key:
1let url = route!(posts::show, &post)?; // http://localhost/posts/4223let response = redirect!(posts::show, &post);1let url = route!(posts::show, &post)?; // http://localhost/posts/4223let response = redirect!(posts::show, &post);
For a route with several parameters, pass them in the order the URI names them, or pass them by name with key = value:
1// http://localhost/posts/42/comments/72let url = route!(comments::show, &post, &comment)?;1// http://localhost/posts/42/comments/72let url = route!(comments::show, &post, &comment)?;
Because your links point at handlers rather than URIs, you may change a route's URI without touching any code that links to it. If you rename or remove a handler, the compiler shows you every route! and redirect! call that still uses it.
If you need to generate a URL in a template, pass route the handler's path, written the way route:list prints it, followed by the route's parameters:
1<a href="{{ route("posts::show", post) }}">{{ post.title }}</a>1<a href="{{ route("posts::show", post) }}">{{ post.title }}</a>
To learn more about generating URLs, including adding query strings and creating signed URLs, check out the URL generation documentation.
Route groups
Route groups let many routes share attributes, such as a prefix or middleware, without repeating them on each route. You may also place a group inside another group. The inner group's prefix is added after the outer group's, and the inner group's routes run the middleware from both groups.
Prefixes
The prefix method adds a URI prefix to each route in the group. For example, you may want every admin route to start with /admin:
1route.prefix("/admin").group(|route| {2 route.get("/users", admin::users::index); // Matches "/admin/users"...3});1route.prefix("/admin").group(|route| {2 route.get("/users", admin::users::index); // Matches "/admin/users"...3});
Middleware
To assign middleware to every route in a group, call middleware before group. You may combine it with other attributes:
1use laravel::auth::Authenticate;23route.prefix("/admin").middleware(Authenticate).group(|route| {4 route.get("/", admin::dashboard);5 route.get("/reports", admin::reports);6});1use laravel::auth::Authenticate;23route.prefix("/admin").middleware(Authenticate).group(|route| {4 route.get("/", admin::dashboard);5 route.get("/reports", admin::reports);6});
You may also assign middleware to a single route. Inside a group, the route runs its own middleware after the group's middleware. Here, every admin page requires a logged-in user, and the billing page also requires a verified email address:
1use laravel::auth::{Authenticate, RequireVerifiedEmail};23route.prefix("/admin").middleware(Authenticate).group(|route| {4 route.get("/", admin::dashboard);5 route.get("/billing", admin::billing).middleware(RequireVerifiedEmail);6});1use laravel::auth::{Authenticate, RequireVerifiedEmail};23route.prefix("/admin").middleware(Authenticate).group(|route| {4 route.get("/", admin::dashboard);5 route.get("/billing", admin::billing).middleware(RequireVerifiedEmail);6});
Sometimes one route in a group shouldn't run one of the group's middleware. Call without_middleware on that route. This status page lives under /admin, but anyone may see it:
1route.prefix("/admin").middleware(Authenticate).group(|route| {2 route.get("/", admin::dashboard);3 route.get("/status", admin::status).without_middleware::<Authenticate>();4});1route.prefix("/admin").middleware(Authenticate).group(|route| {2 route.get("/", admin::dashboard);3 route.get("/status", admin::status).without_middleware::<Authenticate>();4});
without_middleware also works on middleware from the web and api groups, such as CSRF protection, and on a whole group when you call it before group. To learn more, check out the middleware guide's section on excluding middleware.
Domain routing
Use domain to restrict a group to a host. A domain may capture a part of the host as a parameter, such as each customer's account in a multi-tenant application:
1route.domain("admin.example.com").group(|route| {2 route.get("/dashboard", admin::dashboard);3});45route.domain("{account}.example.com").group(|route| {6 route.get("/users/{user}", users::show);7});1route.domain("admin.example.com").group(|route| {2 route.get("/dashboard", admin::dashboard);3});45route.domain("{account}.example.com").group(|route| {6 route.get("/users/{user}", users::show);7});
The second group matches acme.example.com/users/42. Its handler receives the account from the domain along with the user from the path. Domain parameters come first:
1use laravel::prelude::*;23pub async fn show(Params((account, user)): Params<(String, u64)>) -> String {4 format!("User {user} on the {account} account")5}1use laravel::prelude::*;23pub async fn show(Params((account, user)): Params<(String, u64)>) -> String {4 format!("User {user} on the {account} account")5}
Routes with a domain take precedence over routes without one. Among routes with a domain, the first one registered wins, so register specific hosts before patterns such as {account}.example.com.
In production, Laravel only answers requests for the host in your APP_URL and its subdomains. If a domain route uses another domain, such as example.org when your APP_URL is https://example.com, add that domain to your trusted hosts. Otherwise, Laravel rejects its requests with a 400.
When you link to a route on one of these domains, pass the domain's parameters first, then the path's:
1let url = route!(users::show, "acme", 42)?; // http://acme.example.com/users/421let url = route!(users::show, "acme", 42)?; // http://acme.example.com/users/42
To learn more, check out the URL generation guide's section on domain parameters.
Head metadata
with_head gives a route or a group its head metadata, such as its title:
1use laravel::head::{Head, Robots};23route.get("/", welcome::show).with_head(Head::new().title("Welcome"));45route.with_head(Head::new().robots(Robots::None)).prefix("/admin").group(|route| {6 route.get("/dashboard", admin::dashboard).with_head(Head::new().title("Dashboard"));7});1use laravel::head::{Head, Robots};23route.get("/", welcome::show).with_head(Head::new().title("Welcome"));45route.with_head(Head::new().robots(Robots::None)).prefix("/admin").group(|route| {6 route.get("/dashboard", admin::dashboard).with_head(Head::new().title("Dashboard"));7});
When a route and its group both set the same tag, such as the title, Laravel uses the route's value. A handler can still change any tag for its own page by calling head::merge.
Resource routes
Most applications have models that need the same set of create, read, update, and delete (CRUD) routes. A photo gallery, for example, needs a page that lists your photos, a form to upload a new one, a page that shows a single photo, and routes to edit and delete it. Registering those seven routes for every model gets repetitive, so Laravel can register them all at once. Write a module of handlers named after the actions, and register the module with resource!:
1use laravel::routing::resource;23use crate::http::handlers::photos;45pub fn routes(route: &mut Router) {6 resource!(photos);7}1use laravel::routing::resource;23use crate::http::handlers::photos;45pub fn routes(route: &mut Router) {6 resource!(photos);7}
Each public function in photos that has an action's name gets that action's route:
| Method | URI | Handler |
|---|---|---|
GET |
/photos |
photos::index |
GET |
/photos/create |
photos::create |
POST |
/photos |
photos::store |
GET |
/photos/{photo} |
photos::show |
GET |
/photos/{photo}/edit |
photos::edit |
PUT, PATCH |
/photos/{photo} |
photos::update |
DELETE |
/photos/{photo} |
photos::destroy |
A module without create or edit, such as an API module, gets only the other routes.
The routes are ordinary routes, so their handlers may take the photo as a model. Laravel finds the photo by the {photo} parameter, or responds with a 404, and you may link to the route with the model itself:
1// src/http/handlers/photos.rs2use crate::models::Photo;34pub async fn show(photo: Photo) -> String {5 photo.title6}1// src/http/handlers/photos.rs2use crate::models::Photo;34pub async fn show(photo: Photo) -> String {5 photo.title6}
1let url = route!(photos::show, &photo)?; // http://localhost/photos/421let url = route!(photos::show, &photo)?; // http://localhost/photos/42
The resource's name comes from the module's name, with underscores written as dashes, so blog_posts routes /blog-posts/{blog_post}. The parameter is the singular of the name, so photos has {photo} and categories has {category}.
Register only some actions
Sometimes you only want some of the resource's routes. Invoices, for example, may be listed and viewed but never edited, so you may list the actions you want, the same way you'd write a use declaration. When you want most of the actions, it's shorter to name the ones to leave out with except. Here, photos get every route except the create and edit forms:
1use laravel::routing::{Action, resource};23resource!(invoices::{index, show});4resource!(photos).except([Action::Create, Action::Edit]);1use laravel::routing::{Action, resource};23resource!(invoices::{index, show});4resource!(photos).except([Action::Create, Action::Edit]);
Nest a resource in its parent's module
Some resources only make sense inside another one. For example, every comment in a photo gallery is posted on a photo. You'd list the comments on photo 42 at /photos/42/comments, and show a single comment at /photos/42/comments/7. To nest a resource like this, put its handlers in a module inside the parent's module. The comment handlers live in src/http/handlers/photos/comments.rs, declared from the photos module:
1// src/http/handlers/photos.rs2pub mod comments;1// src/http/handlers/photos.rs2pub mod comments;
Then register the nested module. Laravel builds each URI from both modules:
1resource!(photos::comments);1resource!(photos::comments);
| Method | URI | Handler |
|---|---|---|
GET |
/photos/{photo}/comments |
photos::comments::index |
GET |
/photos/{photo}/comments/create |
photos::comments::create |
POST |
/photos/{photo}/comments |
photos::comments::store |
GET |
/photos/{photo}/comments/{comment} |
photos::comments::show |
GET |
/photos/{photo}/comments/{comment}/edit |
photos::comments::edit |
PUT, PATCH |
/photos/{photo}/comments/{comment} |
photos::comments::update |
DELETE |
/photos/{photo}/comments/{comment} |
photos::comments::destroy |
Your handlers may take both the photo and the comment as models. Laravel looks up the photo from {photo} and the comment from {comment}:
1// src/http/handlers/photos/comments.rs2use crate::models::{Comment, Photo};34pub async fn show(photo: Photo, comment: Comment) -> String {5 format!("{} on {}", comment.body, photo.title)6}1// src/http/handlers/photos/comments.rs2use crate::models::{Comment, Photo};34pub async fn show(photo: Photo, comment: Comment) -> String {5 format!("{} on {}", comment.body, photo.title)6}
Once a comment exists, its own ID is often enough to find it, without the photo's ID in front. If you'd like shorter URIs in that case, call shallow. The routes for a single comment then leave the photo out, while the routes for listing and creating comments keep it, since they need to know which photo the comments belong to:
1resource!(photos::comments).shallow();1resource!(photos::comments).shallow();
| Method | URI | Handler |
|---|---|---|
GET |
/photos/{photo}/comments |
photos::comments::index |
GET |
/photos/{photo}/comments/create |
photos::comments::create |
POST |
/photos/{photo}/comments |
photos::comments::store |
GET |
/comments/{comment} |
photos::comments::show |
GET |
/comments/{comment}/edit |
photos::comments::edit |
PUT, PATCH |
/comments/{comment} |
photos::comments::update |
DELETE |
/comments/{comment} |
photos::comments::destroy |
Not every folder of handlers is a parent resource. For example, if you keep your admin pages in src/http/handlers/admin/, resource!(admin::users) would treat admin as a parent and route /admin/{admin}/users. In this situation, since admin isn't an actual resource, import the module and add the /admin prefix with a group:
1use crate::http::handlers::admin::users;23route.prefix("/admin").group(|route| {4 resource!(users); // /admin/users, /admin/users/{user}, ...5});1use crate::http::handlers::admin::users;23route.prefix("/admin").group(|route| {4 resource!(users); // /admin/users, /admin/users/{user}, ...5});
Mark a resource as single
Some resources aren't a list of things. Each user has exactly one profile, so there's no need for an ID in its URIs: /profile shows the logged-in user's profile, and /profile/edit shows the form to change it. To register a resource like this without an ID in its URIs, call single:
1resource!(profile).single();1resource!(profile).single();
With show, edit, and update handlers in the profile module, these routes will be registered:
| Method | URI | Handler |
|---|---|---|
GET |
/profile |
profile::show |
GET |
/profile/edit |
profile::edit |
PUT, PATCH |
/profile |
profile::update |
A single resource may have any action except index, since there's only one of it to list.
Add middleware to some actions
resource! returns the resource's routes, so you may add middleware to all of them with middleware, or to only some of their actions with middleware_for. To keep some actions from running one of the group's middleware, call without_middleware_for. In this example, anyone may browse the photos, but only a logged-in user with a verified email address may upload, change, or delete one:
1use laravel::auth::{Authenticate, RequireVerifiedEmail};2use laravel::routing::{Action, resource};34route.middleware(Authenticate).group(|route| {5 resource!(photos)6 .middleware_for(7 [Action::Store, Action::Update, Action::Destroy],8 RequireVerifiedEmail,9 )10 .without_middleware_for::<Authenticate>([Action::Index, Action::Show]);11});1use laravel::auth::{Authenticate, RequireVerifiedEmail};2use laravel::routing::{Action, resource};34route.middleware(Authenticate).group(|route| {5 resource!(photos)6 .middleware_for(7 [Action::Store, Action::Update, Action::Destroy],8 RequireVerifiedEmail,9 )10 .without_middleware_for::<Authenticate>([Action::Index, Action::Show]);11});
Fallback routes
Without a fallback, a request that matches no route gets a 404 page. The fallback method defines a route that handles those requests instead:
1route.fallback(pages::not_found);1route.fallback(pages::not_found);
Your application's fallback, async || laravel::abort(404), renders unknown pages with its Inertia error page. A fallback in your web route file runs the web middleware group, like the file's other routes. A fallback handles only URIs under its group's prefix, so, for example, an API's fallback handles /api/.. and your web fallback handles everything else.
Before a request reaches your fallback, Laravel serves a matching file from your public directory, if there is one.
Form method spoofing
HTML forms can only send GET and POST requests. To call a PUT, PATCH, or DELETE route from a form, add a hidden _method field. Laravel uses its value as the request method:
1<form action="/posts/1" method="POST">2 <input type="hidden" name="_method" value="DELETE">3 {{ csrf_field() }}4</form>1<form action="/posts/1" method="POST">2 <input type="hidden" name="_method" value="DELETE">3 {{ csrf_field() }}4</form>
In a form that uploads files, put _method before your file inputs. Inertia and other JavaScript clients send real PUT, PATCH, and DELETE requests, so they don't need _method.
Accessing the current route
Sometimes code other than the handler needs to know which route matched, such as middleware that only applies to some pages. To read a domain or path parameter from the request, call request.route. It gives you the parameter as a string, or None when the route has no such parameter:
1if let Some(account) = request.route("account") {2 tracing::info!(account, "Serving an account page");3}1if let Some(account) = request.route("account") {2 tracing::info!(account, "Serving an account page");3}
If you need the parameter as another type, such as a number, use route_as with that type instead. Like a handler's Params, it responds with a 404 when the value doesn't fit the type:
1let user_id: u64 = request.route_as("user")?;1let user_id: u64 = request.route_as("user")?;
The current_route method returns the route that matched the request, and route_is tells you whether a given handler handles it:
1if let Some(route) = request.current_route() {2 route.uri(); // "/users/{user}"3 route.handler(); // "app::http::handlers::users::show"4}56if request.route_is(users::show) {7 // ...8}1if let Some(route) = request.current_route() {2 route.uri(); // "/users/{user}"3 route.handler(); // "app::http::handlers::users::show"4}56if request.route_is(users::show) {7 // ...8}
Global middleware run before routing, so current_route() returns None there. Route middleware and handlers see the matched route.
CORS
When JavaScript on another domain calls your application, such as a single-page app calling your API, browsers first ask whether you allow it. Laravel answers these cross-origin resource sharing (CORS) requests for you, using the cors section of your configuration. By default, any origin may call routes under api/*.
To change who may call your application, edit your application's src/config/cors.rs configuration file. This example adds a webhooks/* path, allows only https://app.example.com, and lets requests carry cookies:
1// src/config/cors.rs2use laravel::config;3use laravel::config::cors::{Allowed, Cors};4use laravel::time::ToSpan;56#[config::section]7fn cors() -> Cors {8 Cors {9 paths: vec!["api/*".to_owned(), "webhooks/*".to_owned()],10 methods: Allowed::Any,11 origins: Allowed::only(["https://app.example.com"]),12 origin_patterns: Vec::new(),13 headers: Allowed::Any,14 exposed_headers: Vec::new(),15 max_age: Some(0.seconds().into()),16 credentials: true,17 }18}1// src/config/cors.rs2use laravel::config;3use laravel::config::cors::{Allowed, Cors};4use laravel::time::ToSpan;56#[config::section]7fn cors() -> Cors {8 Cors {9 paths: vec!["api/*".to_owned(), "webhooks/*".to_owned()],10 methods: Allowed::Any,11 origins: Allowed::only(["https://app.example.com"]),12 origin_patterns: Vec::new(),13 headers: Allowed::Any,14 exposed_headers: Vec::new(),15 max_age: Some(0.seconds().into()),16 credentials: true,17 }18}
| Field | What it allows | Default |
|---|---|---|
paths |
The paths that answer cross-origin requests, where * is a wildcard |
api/* |
origins |
The origins that may call your application, where * is a wildcard: https://*.example.com |
any |
origin_patterns |
Regular expressions for other origins: OriginPattern::new(r"https://pr-\d+\.preview\.dev") |
none |
methods |
The methods they may use | any |
headers |
The request headers they may send | any |
exposed_headers |
The response headers their JavaScript may read | none |
max_age |
How long browsers may cache a preflight's answer | none |
credentials |
Whether requests may carry cookies | false |
The health route
Your application answers health checks from load balancers and uptime monitors at /up, set in src/app.rs:
1.with_routing(|routing, _| {2 routing3 .web(routes::web::routes)4 .api(routes::api::routes)5 .health("/up");6})1.with_routing(|routing, _| {2 routing3 .web(routes::web::routes)4 .api(routes::api::routes)5 .health("/up");6})
It responds with a 200 once your application has booted, and a 503 if it couldn't, such as when a package's boot check failed. It runs before any middleware, so probes by IP address work.
The health route doesn't check your database. If your application shouldn't serve requests while its database is down, query the database in a booted callback in src/app.rs. If the query fails, the application doesn't start:
1use laravel::db;23Application::configure()4 .booted(async |_| {5 db::query!("SELECT 1").statement().await?;67 Ok(())8 })1use laravel::db;23Application::configure()4 .booted(async |_| {5 db::query!("SELECT 1").statement().await?;67 Ok(())8 })