Skip to content

Routing

The Basics

Routing

Basic routing

When someone visits a page in your application or submits a form, Laravel looks at the request's method and path, such as GET /greeting, and finds the route that matches it. The route tells Laravel which function should answer the request. The most basic route pairs a path with a function literal that returns the response:

1package routes
2 
3import (
4 "go.laravel.com/config"
5 "go.laravel.com/routing"
6 "go.laravel.com/web"
7)
8 
9func Web(route *routing.Router, cfg *config.Config) {
10 route.Get("/greeting", func(r *web.Request) *web.Response {
11 return web.Text("Hello World")
12 })
13}
1package routes
2 
3import (
4 "go.laravel.com/config"
5 "go.laravel.com/routing"
6 "go.laravel.com/web"
7)
8 
9func Web(route *routing.Router, cfg *config.Config) {
10 route.Get("/greeting", func(r *web.Request) *web.Response {
11 return web.Text("Hello World")
12 })
13}

Function literals are handy for a quick page, but as your application grows, a route file full of them gets hard to read, because every page's logic sits in one place. So most routes point at a handler instead: a named function in a package under handlers/. The route file stays a short list of paths, and each handler holds the code for one page. A handler receives the request, which holds the route's parameters, and returns a response:

1import (
2 "go.laravel.com/config"
3 "go.laravel.com/routing"
4 
5 "app/handlers/users"
6)
7 
8func Web(route *routing.Router, cfg *config.Config) {
9 route.Get("/users", users.Index)
10 route.Get("/users/{user}", users.Show)
11 route.Post("/users", users.Store)
12}
1import (
2 "go.laravel.com/config"
3 "go.laravel.com/routing"
4 
5 "app/handlers/users"
6)
7 
8func Web(route *routing.Router, cfg *config.Config) {
9 route.Get("/users", users.Index)
10 route.Get("/users/{user}", users.Show)
11 route.Post("/users", users.Store)
12}

The default route files

Your routes live in two functions in the routes package, Web and API. Your application passes both functions to Laravel in bootstrap/app.go:

1package bootstrap
2 
3import (
4 laravel "go.laravel.com"
5 
6 "app/routes"
7)
8 
9func Options() laravel.Options {
10 return laravel.Options{
11 Routes: laravel.Routes{
12 Web: routes.Web,
13 API: routes.API,
14 Health: "/up",
15 },
16 }
17}
1package bootstrap
2 
3import (
4 laravel "go.laravel.com"
5 
6 "app/routes"
7)
8 
9func Options() laravel.Options {
10 return laravel.Options{
11 Routes: laravel.Routes{
12 Web: routes.Web,
13 API: routes.API,
14 Health: "/up",
15 },
16 }
17}

For most applications, you'll start by defining routes in routes/web.go. These are the pages that browsers visit, and they run within the web middleware group, which gives them encrypted cookies, a session, and CSRF protection.

If other applications, scripts, or services will call your application's API, define those routes in routes/api.go. These routes are stateless, and they run within the api middleware group, which is empty by default. Laravel adds /api to the start of every path in routes/api.go, so a /users route defined in that file answers at /api/users. The errors of these routes are always JSON. If your application has no API, leave API out of the options.

You may put your API under another prefix, such as one with a version number. Set APIPrefix beside your route functions in bootstrap/app.go:

1Routes: laravel.Routes{
2 Web: routes.Web,
3 API: routes.API,
4 APIPrefix: "/api/v1",
5},
1Routes: laravel.Routes{
2 Web: routes.Web,
3 API: routes.API,
4 APIPrefix: "/api/v1",
5},

By default, CORS only lets other origins call paths under /api. If your prefix starts somewhere else, such as /v1, add its paths to the CORS middleware's Paths too.

Sometimes you need routes that belong in neither file, such as a payment provider's webhooks. Webhooks don't come from a browser, so they need no session or CSRF check, and the provider expects them at a path you choose, such as /webhooks/stripe, rather than under /api. Register these routes in a function of their own, and pass it to Laravel as Bare. Its routes get no session, no CSRF check, and no prefix, so you choose their middleware yourself:

1// bootstrap/app.go
2Routes: laravel.Routes{
3 Web: routes.Web,
4 API: routes.API,
5 Bare: routes.Webhooks,
6 Health: "/up",
7},
1// bootstrap/app.go
2Routes: laravel.Routes{
3 Web: routes.Web,
4 API: routes.API,
5 Bare: routes.Webhooks,
6 Health: "/up",
7},
1// routes/webhooks.go
2package routes
3 
4import (
5 "go.laravel.com/config"
6 "go.laravel.com/routing"
7 
8 "app/handlers/webhooks"
9 "app/stripe"
10)
11 
12func Webhooks(route *routing.Router, cfg *config.Config) {
13 route.Middleware(stripe.VerifySignature{}).Post("/webhooks/stripe", webhooks.Stripe)
14}
1// routes/webhooks.go
2package routes
3 
4import (
5 "go.laravel.com/config"
6 "go.laravel.com/routing"
7 
8 "app/handlers/webhooks"
9 "app/stripe"
10)
11 
12func Webhooks(route *routing.Router, cfg *config.Config) {
13 route.Middleware(stripe.VerifySignature{}).Post("/webhooks/stripe", webhooks.Stripe)
14}

Each route function receives your application's configuration, so you may register some routes only in some environments. For example, a page that previews your emails is useful while you work on them, but it shouldn't exist in production:

1// routes/web.go
2func Web(route *routing.Router, cfg *config.Config) {
3 route.Get("/", welcome.Show)
4 
5 if cfg.App.Env == config.Local {
6 route.Get("/previews/welcome-email", previews.WelcomeEmail)
7 }
8}
1// routes/web.go
2func Web(route *routing.Router, cfg *config.Config) {
3 route.Get("/", welcome.Show)
4 
5 if cfg.App.Env == config.Local {
6 route.Get("/previews/welcome-email", previews.WelcomeEmail)
7 }
8}

Available router methods

The router has a method for each HTTP method:

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 answers HEAD requests. To answer several methods, use Match. To answer every method, use Any:

1import "net/http"
2 
3route.Match([]string{http.MethodGet, http.MethodPost}, "/search", search.Show)
4 
5route.Any("/webhooks/stripe", webhooks.Stripe)
1import "net/http"
2 
3route.Match([]string{http.MethodGet, http.MethodPost}, "/search", search.Show)
4 
5route.Any("/webhooks/stripe", webhooks.Stripe)

Some libraries give you a standard http.Handler, such as a metrics endpoint, rather than a Laravel handler. To learn how to mount one with route.Handle, check out the handlers guide's section on standard handlers.

Redirect routes

A route that only redirects to another URI doesn't need a handler. Use Redirect for a 302, or PermanentRedirect for a 301:

1route.Redirect("/here", "/there")
2 
3route.PermanentRedirect("/here", "/there")
1route.Redirect("/here", "/there")
2 
3route.PermanentRedirect("/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.PermanentRedirect("/posts/{post}", "/articles/{post}")
2 
3route.PermanentRedirect("/blog/{slug...}", "https://blog.example.com/{slug...}")
1route.PermanentRedirect("/posts/{post}", "/articles/{post}")
2 
3route.PermanentRedirect("/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. A handler that only renders the page would be a function with nothing in it, so the route may render a view or an Inertia page component itself. Use View with the view's name and its data, or Inertia with the name of the page component:

1route.View("/about", "about", nil)
2 
3route.Inertia("/pricing", "Pricing")
1route.View("/about", "about", nil)
2 
3route.Inertia("/pricing", "Pricing")

The view receives the data you pass, here nil, along with the data shared with every view. The page component receives only your shared props. When a page needs data from the database or the request, write a handler.

Listing your routes

The route:list console command gives you an overview of every route your application defines. It lists each route's method, URI, handler, and name:

1laravel route:list
1laravel route:list

You may also add a few options to the command. --middleware (or -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, by name with --name=users, by handler with --handler=photos, or by method with --method=POST.

Route parameters

To capture a segment of the path, such as a user's ID, define a route parameter in braces. Each parameter fills a whole segment, so /users/user-{id} isn't a valid path:

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 read each parameter by its name with r.PathValue, which returns the segment as a string. When you need the parameter as a number, call r.PathInt instead, which returns an int64. If the segment isn't an integer, such as /users/taylor, PathInt returns an error, and passing that error to web.Fail responds with a 404:

1package comments
2 
3import (
4 "fmt"
5 
6 "go.laravel.com/web"
7)
8 
9func Show(r *web.Request) *web.Response {
10 post, err := r.PathInt("post")
11 if err != nil {
12 return web.Fail(err)
13 }
14 
15 return web.Text(fmt.Sprintf("Comment %s on post %d", r.PathValue("comment"), post))
16}
1package comments
2 
3import (
4 "fmt"
5 
6 "go.laravel.com/web"
7)
8 
9func Show(r *web.Request) *web.Response {
10 post, err := r.PathInt("post")
11 if err != nil {
12 return web.Fail(err)
13 }
14 
15 return web.Text(fmt.Sprintf("Comment %s on post %d", r.PathValue("comment"), post))
16}

A wildcard parameter, written with ... after its name, captures the rest of the path, including its slashes. The wildcard must be the path's last segment. For example, a request for /files/reports/2026/summary.pdf reaches this route, and r.PathValue("path") returns reports/2026/summary.pdf:

1route.Get("/files/{path...}", files.Show)
1route.Get("/files/{path...}", files.Show)

When several routes match a path, Laravel chooses the most specific route, not the first one you registered. A fixed segment such as create is more specific than a parameter such as {user}, and a parameter is more specific than a wildcard such as {path...}. So /users/create reaches a /users/create route even if you registered /users/{user} first. If neither of two routes is more specific, such as /teams/{team}/new and /teams/all/{view}, which both match /teams/all/new, your application refuses to start, and Laravel names the file and line that registered each route.

A wildcard may hold .., which climbs out of a directory. If you open a file that a wildcard names, open it with os.OpenInRoot, which refuses a path outside its directory.

Optional parameters

Add ? to a parameter's name to make its segment optional. Optional parameters must come at the end of the path:

1route.Get("/archive/{year?}/{month?}", archive.Show)
1route.Get("/archive/{year?}/{month?}", archive.Show)

This route matches /archive, /archive/2026, and /archive/2026/10. When the request leaves a parameter out, PathValue returns "", so your handler chooses what a missing parameter means:

1func Show(r *web.Request) *web.Response {
2 year := r.PathValue("year")
3 if year == "" {
4 return web.Text("All archives")
5 }
6 
7 return web.Text("Archive for " + year + ", month " + r.PathValue("month"))
8}
1func Show(r *web.Request) *web.Response {
2 year := r.PathValue("year")
3 if year == "" {
4 return web.Text("All archives")
5 }
6 
7 return web.Text("Archive for " + year + ", month " + r.PathValue("month"))
8}

Restricting parameter values

A parameter matches any text in its segment, but many routes only make sense for some values. For example, a user's ID is a number, so /users/taylor should be a 404 rather than reach your handler. Chain Where onto the route with the parameter's name and a constraint from the routing package:

1import "go.laravel.com/routing"
2 
3route.Get("/users/{user}", users.Show).Where("user", routing.Number)
1import "go.laravel.com/routing"
2 
3route.Get("/users/{user}", users.Show).Where("user", routing.Number)

A request whose parameter doesn't fit gets a 404, before the route's middleware and handler run. An optional parameter that the request leaves out isn't checked. These are the constraints the routing package provides:

Constraint Accepts
routing.Number Digits, such as 42
routing.Alpha Letters, such as taylor
routing.AlphaNumeric Letters and digits, such as abc123
routing.UUID A UUID, such as 9b1deb4d-3b7d-4bad-9bdd-2b0d7b3dcb6d
routing.ULID A ULID, such as 01ARZ3NDEKTSV4RRFFQ69G5FAV
routing.In(values...) Only the values you list
routing.Matches(pattern) Text that the regular expression matches as a whole

For example, a store may sell only movies, songs, and paintings, and its posts may have slugs of lowercase letters, digits, and dashes:

1route.Get("/categories/{category}", categories.Show).
2 Where("category", routing.In("movies", "songs", "paintings"))
3 
4route.Get("/posts/{slug}", posts.Show).Where("slug", routing.Matches(`[a-z0-9-]+`))
1route.Get("/categories/{category}", categories.Show).
2 Where("category", routing.In("movies", "songs", "paintings"))
3 
4route.Get("/posts/{slug}", posts.Show).Where("slug", routing.Matches(`[a-z0-9-]+`))

With these routes, /categories/songs reaches the store's songs and /categories/podcasts is a 404. A constraint is a func(string) bool, so you may also pass a function of your own.

If many routes share a parameter, such as an id in every admin route, call Where on the router instead. The routes you register on the router it returns restrict the parameter, and routes without the parameter are unaffected. A route's own Where replaces the router's for the same parameter:

1admin := route.Prefix("/admin").Where("id", routing.Number)
2 
3admin.Get("/users/{id}", adminusers.Show)
4admin.Get("/teams/{id}", adminteams.Show)
1admin := route.Prefix("/admin").Where("id", routing.Number)
2 
3admin.Get("/users/{id}", adminusers.Show)
4admin.Get("/teams/{id}", adminteams.Show)

Where restricts a domain parameter too, such as the {account} in {account}.example.com.

Models in route parameters

When a parameter holds a model's ID, such as the post's ID in /posts/{post}, call model.FromRoute in your handler to find the model. If no post has that ID, or the value isn't an ID at all, FromRoute returns an error that responds with a 404:

1package posts
2 
3import (
4 "go.laravel.com/model"
5 "go.laravel.com/web"
6 
7 "app/models"
8)
9 
10func Show(r *web.Request) *web.Response {
11 post, err := model.FromRoute[models.Post](r, "post")
12 if err != nil {
13 return web.Fail(err)
14 }
15 
16 return web.JSON(post)
17}
1package posts
2 
3import (
4 "go.laravel.com/model"
5 "go.laravel.com/web"
6 
7 "app/models"
8)
9 
10func Show(r *web.Request) *web.Response {
11 post, err := model.FromRoute[models.Post](r, "post")
12 if err != nil {
13 return web.Fail(err)
14 }
15 
16 return web.JSON(post)
17}

To find the post by another column, such as its slug, name the column after a colon, as in /blog/{post:slug}, and model.FromRoute looks the post up by that column. FromRoute works in middleware too, because it only needs the request. In a nested route such as /users/{user}/posts/{post}, find the post through its user, so one user's post never shows under another user's URL. To learn more, check out the models guide's section on finding a model from a route.

Named routes

A name lets the rest of your application link to a route without repeating its path. To name a route, chain Name onto its definition:

1route.Get("/users/{user}", users.Show).Name("users.show")
1route.Get("/users/{user}", users.Show).Name("users.show")

In a handler or middleware, pass the name and the route's parameters to urls.Route to generate the route's URL, or to web.RedirectRoute to redirect to it:

1import (
2 "go.laravel.com/urls"
3 "go.laravel.com/web"
4)
5 
6link, err := urls.Route(r, "users.show", "user", 7) // http://localhost/users/7
7 
8return web.RedirectRoute("users.show", "user", 7)
1import (
2 "go.laravel.com/urls"
3 "go.laravel.com/web"
4)
5 
6link, err := urls.Route(r, "users.show", "user", 7) // http://localhost/users/7
7 
8return web.RedirectRoute("users.show", "user", 7)

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 the model sets another column with RouteKeyName, or with the column that the route names, such as the slug for /blog/{post:slug}:

1link, err := urls.Route(r, "posts.show", "post", &post) // http://localhost/posts/42
2 
3return web.RedirectRoute("blog.show", "post", &post) // http://localhost/blog/hello-world
1link, err := urls.Route(r, "posts.show", "post", &post) // http://localhost/posts/42
2 
3return web.RedirectRoute("blog.show", "post", &post) // http://localhost/blog/hello-world

For a route with several parameters, pass each name and value in turn. Models work here too:

1// http://localhost/posts/42/comments/7
2link, err := urls.Route(r, "comments.show", "post", &post, "comment", &comment)
1// http://localhost/posts/42/comments/7
2link, err := urls.Route(r, "comments.show", "post", &post, "comment", &comment)

Because your links name the route rather than its path, you may change the route's path later without touching any code that links to it.

If you need to link to a route in a view, pass route the route's name, followed by its parameters as names and values:

1<a href="{{route "posts.show" "post" .Post.ID}}">{{.Post.Title}}</a>
1<a href="{{route "posts.show" "post" .Post.ID}}">{{.Post.Title}}</a>

To learn more about generating URLs, including adding query strings and creating signed URLs, check out the URL generation guide.

Route groups

Routes often share a prefix, middleware, or a domain. For example, every route in an admin area may start with /admin and need a signed-in user. Rather than repeat those settings on each route, ask the router for another router that has them. Prefix, Name, Middleware, and Domain each return a new router that registers routes into the same application, so you may keep a group of routes in a variable. Here, auth.Authenticate sends visitors who haven't signed in to the login page:

1import "go.laravel.com/auth"
2 
3admin := route.Prefix("/admin").Middleware(auth.Authenticate{})
4 
5admin.Get("/", dashboard.Show)
6admin.Get("/users", adminusers.Index)
1import "go.laravel.com/auth"
2 
3admin := route.Prefix("/admin").Middleware(auth.Authenticate{})
4 
5admin.Get("/", dashboard.Show)
6admin.Get("/users", adminusers.Index)

The original router doesn't change, so the routes you register on route afterward have neither the prefix nor the middleware.

If you'd like the group's routes indented under their settings, call Group with a function that receives the new router. This example registers the same routes as the previous example:

1route.Prefix("/admin").Middleware(auth.Authenticate{}).Group(func(route *routing.Router) {
2 route.Get("/", dashboard.Show)
3 route.Get("/users", adminusers.Index)
4})
1route.Prefix("/admin").Middleware(auth.Authenticate{}).Group(func(route *routing.Router) {
2 route.Get("/", dashboard.Show)
3 route.Get("/users", adminusers.Index)
4})

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 path to the start of every route in the group. For example, you may want every admin route to start with /admin:

1admin := route.Prefix("/admin")
2 
3admin.Get("/users", adminusers.Index) // Answers /admin/users.
1admin := route.Prefix("/admin")
2 
3admin.Get("/users", adminusers.Index) // Answers /admin/users.

Middleware

To run middleware on every route in a group, call Middleware. You may combine it with other settings, such as a prefix. Laravel runs the middleware in the order you list them:

1admin := route.Prefix("/admin").Middleware(auth.Authenticate{})
2 
3admin.Get("/", dashboard.Show)
4admin.Get("/reports", reports.Index)
1admin := route.Prefix("/admin").Middleware(auth.Authenticate{})
2 
3admin.Get("/", dashboard.Show)
4admin.Get("/reports", reports.Index)

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 signed-in user, and the billing page also requires a verified email address:

1admin := route.Prefix("/admin").Middleware(auth.Authenticate{})
2 
3admin.Get("/", dashboard.Show)
4admin.Get("/billing", billing.Show).Middleware(auth.RequireVerifiedEmail{})
1admin := route.Prefix("/admin").Middleware(auth.Authenticate{})
2 
3admin.Get("/", dashboard.Show)
4admin.Get("/billing", billing.Show).Middleware(auth.RequireVerifiedEmail{})

Sometimes one route in a group shouldn't run one of the group's middleware. Call Without on that route. This status page lives under /admin, but anyone may see it:

1admin := route.Prefix("/admin").Middleware(auth.Authenticate{})
2 
3admin.Get("/", dashboard.Show)
4admin.Get("/status", status.Show).Without(auth.Authenticate{})
1admin := route.Prefix("/admin").Middleware(auth.Authenticate{})
2 
3admin.Get("/", dashboard.Show)
4admin.Get("/status", status.Show).Without(auth.Authenticate{})

Without also works on middleware from the web and api groups, such as CSRF protection, and on a whole group when you call it on a router, as in route.Without(middleware.ValidateCSRFToken{}). To learn more, check out the middleware guide's section on excluding middleware.

Route name prefixes

An admin area often has routes that mirror your public ones, such as a list of users in each, and their names would collide. The Name method adds a prefix to the name of every route in the group. Laravel adds the prefix exactly as you write it, so end the prefix with a .:

1admin := route.Prefix("/admin").Name("admin.")
2 
3admin.Get("/users", adminusers.Index).Name("users.index") // Named admin.users.index.
1admin := route.Prefix("/admin").Name("admin.")
2 
3admin.Get("/users", adminusers.Index).Name("users.index") // Named admin.users.index.

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(func(route *routing.Router) {
2 route.Get("/dashboard", admin.Dashboard)
3})
4 
5route.Domain("{account}.example.com").Group(func(route *routing.Router) {
6 route.Get("/users/{user}", users.Show)
7})
1route.Domain("admin.example.com").Group(func(route *routing.Router) {
2 route.Get("/dashboard", admin.Dashboard)
3})
4 
5route.Domain("{account}.example.com").Group(func(route *routing.Router) {
6 route.Get("/users/{user}", users.Show)
7})

The second group matches acme.example.com/users/42. Its handler reads the account from the domain with r.PathValue, the same method that reads the user from the path:

1func Show(r *web.Request) *web.Response {
2 account, user := r.PathValue("account"), r.PathValue("user")
3 
4 return web.Text("User " + user + " on the " + account + " account")
5}
1func Show(r *web.Request) *web.Response {
2 account, user := r.PathValue("account"), r.PathValue("user")
3 
4 return web.Text("User " + user + " on the " + account + " account")
5}

A domain parameter matches one part of the host, so {account}.example.com matches acme.example.com but not eu.acme.example.com. Routes with a domain take precedence over routes without one, and a domain with fewer parameters takes precedence over one with more, so admin.example.com reaches its own routes whichever group you register first.

In production, Laravel only answers requests for the host in your APP_URL and its subdomains. If a domain route uses another host, such as example.org when your APP_URL is https://example.com, add that host 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 along with the path's:

1// http://acme.example.com/users/42
2link, err := urls.Route(r, "users.show", "account", "acme", "user", 42)
1// http://acme.example.com/users/42
2link, err := urls.Route(r, "users.show", "account", "acme", "user", 42)

To learn more, check out the URL generation guide's section on domain parameters.

Head metadata

WithHead gives a route or a group its head metadata, such as a page title or a robots rule. For example, search engines shouldn't index an admin area, and its dashboard needs a title:

1import "go.laravel.com/head"
2 
3admin := route.Prefix("/admin").WithHead(head.Head{Robots: "noindex, nofollow"})
4 
5admin.Get("/dashboard", dashboard.Show).WithHead(head.Head{Title: "Dashboard"})
1import "go.laravel.com/head"
2 
3admin := route.Prefix("/admin").WithHead(head.Head{Robots: "noindex, nofollow"})
4 
5admin.Get("/dashboard", dashboard.Show).WithHead(head.Head{Title: "Dashboard"})

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. Pass Resource the resource's name and the handlers for its actions:

1import (
2 "go.laravel.com/routing"
3 
4 "app/handlers/photos"
5)
6 
7route.Resource("photos", routing.Resource{
8 Index: photos.Index,
9 Create: photos.Create,
10 Store: photos.Store,
11 Show: photos.Show,
12 Edit: photos.Edit,
13 Update: photos.Update,
14 Destroy: photos.Destroy,
15})
1import (
2 "go.laravel.com/routing"
3 
4 "app/handlers/photos"
5)
6 
7route.Resource("photos", routing.Resource{
8 Index: photos.Index,
9 Create: photos.Create,
10 Store: photos.Store,
11 Show: photos.Show,
12 Edit: photos.Edit,
13 Update: photos.Update,
14 Destroy: photos.Destroy,
15})

Each field you set gets its action's route and name:

Field Method URI Route name
Index GET /photos photos.index
Create GET /photos/create photos.create
Store POST /photos photos.store
Show GET /photos/{photo} photos.show
Edit GET /photos/{photo}/edit photos.edit
Update PUT or PATCH /photos/{photo} photos.update
Destroy DELETE /photos/{photo} photos.destroy

A field that you leave out gets no route. For example, an API that only lists and shows photos sets Index and Show.

The routes are ordinary routes, so their handlers may find the photo as a model. model.FromRoute finds the photo by the {photo} parameter, or returns an error that responds with a 404, and you may link to the route with the model itself:

1// handlers/photos/photos.go
2func Show(r *web.Request) *web.Response {
3 photo, err := model.FromRoute[models.Photo](r, "photo")
4 if err != nil {
5 return web.Fail(err)
6 }
7 
8 return web.Text(photo.Title)
9}
1// handlers/photos/photos.go
2func Show(r *web.Request) *web.Response {
3 photo, err := model.FromRoute[models.Photo](r, "photo")
4 if err != nil {
5 return web.Fail(err)
6 }
7 
8 return web.Text(photo.Title)
9}
1link, err := urls.Route(r, "photos.show", "photo", &photo) // http://localhost/photos/42
1link, err := urls.Route(r, "photos.show", "photo", &photo) // http://localhost/photos/42

The parameter is the singular of the resource's name, with dashes written as underscores. So photos has {photo}, and blog-posts has {blog_post}, which a handler reads with r.PathValue("blog_post"). If you'd like another name, set the Parameter field:

1route.Resource("categories", routing.Resource{
2 Show: categories.Show,
3 Parameter: "slug",
4})
1route.Resource("categories", routing.Resource{
2 Show: categories.Show,
3 Parameter: "slug",
4})

To give a resource a prefix or middleware, register the resource on a group.

Nested resources

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, register it on a group with the parent's path as its prefix and a name prefix. The comment handlers then read both the photo and comment parameters:

1route.Prefix("/photos/{photo}").Name("photos.").Resource("comments", routing.Resource{
2 Index: comments.Index, // GET /photos/{photo}/comments, named photos.comments.index.
3 Store: comments.Store,
4 Show: comments.Show, // GET /photos/{photo}/comments/{comment}, named photos.comments.show.
5})
1route.Prefix("/photos/{photo}").Name("photos.").Resource("comments", routing.Resource{
2 Index: comments.Index, // GET /photos/{photo}/comments, named photos.comments.index.
3 Store: comments.Store,
4 Show: comments.Show, // GET /photos/{photo}/comments/{comment}, named photos.comments.show.
5})

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, register the actions on a single comment as a resource of their own. The routes for listing and storing comments stay under the photo, because they need to know which photo the comments belong to:

1route.Prefix("/photos/{photo}").Name("photos.").Resource("comments", routing.Resource{
2 Index: comments.Index, // GET /photos/{photo}/comments
3 Store: comments.Store, // POST /photos/{photo}/comments
4})
5 
6route.Resource("comments", routing.Resource{
7 Show: comments.Show, // GET /comments/{comment}
8 Update: comments.Update, // PUT /comments/{comment}
9 Destroy: comments.Destroy, // DELETE /comments/{comment}
10})
1route.Prefix("/photos/{photo}").Name("photos.").Resource("comments", routing.Resource{
2 Index: comments.Index, // GET /photos/{photo}/comments
3 Store: comments.Store, // POST /photos/{photo}/comments
4})
5 
6route.Resource("comments", routing.Resource{
7 Show: comments.Show, // GET /comments/{comment}
8 Update: comments.Update, // PUT /comments/{comment}
9 Destroy: comments.Destroy, // DELETE /comments/{comment}
10})

Singleton resources

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 signed-in user's profile, and /profile/edit shows the form to change it. To register a resource like this, call Singleton. A singleton may have any action except Index, because there's only one of it to list:

1route.Singleton("profile", routing.Singleton{
2 Show: profile.Show, // GET /profile, named profile.show.
3 Edit: profile.Edit, // GET /profile/edit
4 Update: profile.Update, // PUT or PATCH /profile
5})
1route.Singleton("profile", routing.Singleton{
2 Show: profile.Show, // GET /profile, named profile.show.
3 Edit: profile.Edit, // GET /profile/edit
4 Update: profile.Update, // PUT or PATCH /profile
5})

A singleton may also belong to another resource. For example, each user has one avatar at /users/{user}/avatar:

1route.Prefix("/users/{user}").Name("users.").Singleton("avatar", routing.Singleton{
2 Show: avatars.Show, // GET /users/{user}/avatar, named users.avatar.show.
3 Update: avatars.Update,
4})
1route.Prefix("/users/{user}").Name("users.").Singleton("avatar", routing.Singleton{
2 Show: avatars.Show, // GET /users/{user}/avatar, named users.avatar.show.
3 Update: avatars.Update,
4})

Middleware on some actions

Sometimes only some of a resource's actions need a middleware. Each action is an ordinary route, so you may register some actions through one router and the rest through another. In this example, any signed-in user may list and show photos, but only a user who has verified their email address may store, change, or delete one:

1signedIn := route.Middleware(auth.Authenticate{})
2 
3signedIn.Resource("photos", routing.Resource{
4 Index: photos.Index,
5 Show: photos.Show,
6})
7 
8signedIn.Middleware(auth.RequireVerifiedEmail{}).Resource("photos", routing.Resource{
9 Store: photos.Store,
10 Update: photos.Update,
11 Destroy: photos.Destroy,
12})
1signedIn := route.Middleware(auth.Authenticate{})
2 
3signedIn.Resource("photos", routing.Resource{
4 Index: photos.Index,
5 Show: photos.Show,
6})
7 
8signedIn.Middleware(auth.RequireVerifiedEmail{}).Resource("photos", routing.Resource{
9 Store: photos.Store,
10 Update: photos.Update,
11 Destroy: photos.Destroy,
12})

Every route keeps its conventional path and name, such as photos.store. To keep some actions from running one of the group's middleware, register those actions on a router from Without.

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.NotFound)
1route.Fallback(pages.NotFound)

New applications end routes/web.go with a fallback that returns web.Abort(http.StatusNotFound). A fallback in routes/web.go runs the web middleware group like the file's other routes, so unknown pages render as your Inertia error page. A fallback handles only paths under its group's prefix. For example, a fallback registered on route.Prefix("/v2") handles unknown paths under /v2, and the fallback at the end of routes/web.go handles everything else.

Before a request reaches your fallback, Laravel serves a matching file from your application's public directory, if there is one. For example, a request for /robots.txt gets public/robots.txt.

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 the field's value as the request's method. In a view, methodField writes the field for you:

1<form action="/photos/7" method="POST">
2 {{methodField "DELETE"}}
3 {{csrfField}}
4 
5 <button>Delete photo</button>
6</form>
1<form action="/photos/7" method="POST">
2 {{methodField "DELETE"}}
3 {{csrfField}}
4 
5 <button>Delete photo</button>
6</form>

In a form that uploads files, put the _method field before your file inputs, because Laravel only looks for the field at the start of the body. 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 a middleware that only applies to some pages. A route middleware reads a domain or path parameter with r.PathValue, as a handler does, and gets "" when the route has no such parameter:

1if account := r.PathValue("account"); account != "" {
2 slog.InfoContext(r, "Serving an account page", "account", account)
3}
1if account := r.PathValue("account"); account != "" {
2 slog.InfoContext(r, "Serving an account page", "account", account)
3}

r.Route() returns the route that matched the request. Its fields hold the route's name, URI, domain, methods, and handler:

1current := r.Route()
2 
3current.Name // "users.show"
4current.URI // "/users/{user}"
5current.Handler // "app/handlers/users.Show"
1current := r.Route()
2 
3current.Name // "users.show"
4current.URI // "/users/{user}"
5current.Handler // "app/handlers/users.Show"

To check the route's name against one or more patterns, call r.RouteIs. A * in a pattern stands for any text:

1if r.RouteIs("admin.*") {
2 // ...
3}
1if r.RouteIs("admin.*") {
2 // ...
3}

Global middleware runs before routing, so r.Route() returns an empty route there. Route middleware and handlers see the route that matched.

Request limits

A server that accepts request bodies of any size lets one client fill its memory or disk. So Laravel limits every request body, and responds with a 413 Content Too Large when a request goes over a limit:

Limit Default What it limits
Body 2 MiB The size of a JSON or form body.
Uploads 16 MiB The size of a multipart body, including its files.
Fields 1000 The number of fields in a JSON body, form body, or query string.
Files 20 The number of files in a body.

The defaults suit most routes, but some routes need more room, such as a video upload. Call Limits on that route to raise its limit, and the rest of your application keeps the defaults. Pass web.NoLimit to remove a limit on a route that streams its own request body:

1import "go.laravel.com/web"
2 
3route.Post("/videos", videos.Store).Limits(web.Limits{Uploads: 512 << 20})
4route.Post("/streams", streams.Ingest).Limits(web.Limits{Body: web.NoLimit})
1import "go.laravel.com/web"
2 
3route.Post("/videos", videos.Store).Limits(web.Limits{Uploads: 512 << 20})
4route.Post("/streams", streams.Ingest).Limits(web.Limits{Body: web.NoLimit})

You may also call Limits on a router, such as route.Prefix("/imports").Limits(...), to change the limits of every route in the group. A field that you leave at zero keeps the limit the route already had. To change the default number of fields and files for your whole application, set SERVER_MAX_INPUT_VARS and SERVER_MAX_FILE_UPLOADS in your .env file.

Timeouts

A handler that waits forever on a slow query holds a connection open, and enough of them leave no room for other visitors. So each route has 30 seconds to answer. If a route takes longer, the visitor gets a 503 Service Unavailable, and Laravel reports an error that names the route.

Some routes need more time, such as one that builds a large report. Call Timeout on a route or a group to change its timeout. A timeout of zero lets the route take as long as it needs:

1import "time"
2 
3route.Post("/reports", reports.Store).Timeout(2 * time.Minute)
4 
5exports := route.Prefix("/exports").Timeout(5 * time.Minute)
1import "time"
2 
3route.Post("/reports", reports.Store).Timeout(2 * time.Minute)
4 
5exports := route.Prefix("/exports").Timeout(5 * time.Minute)

The timeout covers the route's middleware and handler, but not sending the response, so a streamed response or a large download may keep going past it.

At the deadline, Laravel answers the visitor and cancels the request's context, but it can't stop your handler. Pass r to every query and HTTP call, so their work stops too.

CORS

When JavaScript on another origin calls your application, such as a single-page app on app.example.com calling your API, the browser first asks whether you allow it. Laravel's HandleCORS middleware answers these cross-origin resource sharing (CORS) requests for you. By default, any origin may call the paths under /api, and no other paths.

To change who may call your application, replace the middleware in the Middleware option of bootstrap/app.go. This example allows only https://app.example.com, lets its requests carry cookies, and lets browsers remember the answer for an hour:

1import (
2 "time"
3 
4 laravel "go.laravel.com"
5 "go.laravel.com/config"
6 "go.laravel.com/middleware"
7)
8 
9Middleware: func(m *laravel.Middleware, cfg *config.Config) {
10 m.Replace(middleware.HandleCORS{
11 Paths: []string{"api/*"},
12 AllowedOrigins: []string{"https://app.example.com"},
13 AllowCredentials: true,
14 MaxAge: time.Hour,
15 })
16},
1import (
2 "time"
3 
4 laravel "go.laravel.com"
5 "go.laravel.com/config"
6 "go.laravel.com/middleware"
7)
8 
9Middleware: func(m *laravel.Middleware, cfg *config.Config) {
10 m.Replace(middleware.HandleCORS{
11 Paths: []string{"api/*"},
12 AllowedOrigins: []string{"https://app.example.com"},
13 AllowCredentials: true,
14 MaxAge: time.Hour,
15 })
16},

These are the settings HandleCORS takes:

Field What it allows When empty
Paths The paths that answer other origins, where * stands for any text api/*
AllowedOrigins The origins that may call your application, such as https://*.example.com Every origin, unless you set AllowedOriginPatterns
AllowedOriginPatterns Regular expressions for other origins that may call your application None
AllowedMethods The methods other origins may use Every method
AllowedHeaders The request headers other origins may send Every header
ExposedHeaders The response headers their JavaScript may read None
MaxAge How long a browser may remember a preflight's answer The browser's default
AllowCredentials Whether requests may carry the visitor's cookies false

When you need to allow origins that follow a pattern a * can't express, such as a preview deployment for each pull request at https://pr-42.preview.example.com, list a regular expression for them in AllowedOriginPatterns. Laravel allows an origin when the expression matches any part of it, so start the expression with ^ and end it with $ to match the whole origin:

1m.Replace(middleware.HandleCORS{
2 AllowedOrigins: []string{"https://app.example.com"},
3 AllowedOriginPatterns: []*regexp.Regexp{
4 regexp.MustCompile(`^https://pr-\d+\.preview\.example\.com$`),
5 },
6})
1m.Replace(middleware.HandleCORS{
2 AllowedOrigins: []string{"https://app.example.com"},
3 AllowedOriginPatterns: []*regexp.Regexp{
4 regexp.MustCompile(`^https://pr-\d+\.preview\.example\.com$`),
5 },
6})

If you set AllowCredentials, also list the origins you trust in AllowedOrigins or AllowedOriginPatterns. Otherwise, any site may call your application as the signed-in visitor.

The health route

Load balancers, container platforms, and uptime monitors ask your application whether it's up before they send it traffic. New applications answer them at /up, which the Health option sets in bootstrap/app.go:

1Routes: laravel.Routes{
2 Web: routes.Web,
3 Health: "/up",
4},
1Routes: laravel.Routes{
2 Web: routes.Web,
3 Health: "/up",
4},

The health route answers GET requests with a 200 before any middleware runs, so a check needs no session and works on any host. If you'd rather have no health route, leave Health empty.