跳至正文

URL Generation ​

Introduction ​

The urls package provides functions for generating absolute URLs to your application's routes and paths. For example, when you build an API response that links to a post's comments, or send a customer an email with an unsubscribe link, urls builds the full URL using the right scheme and host.

You may also generate signed URLs that protect route and query parameters from tampering, or expire automatically after a period of time.

Configuration ​

Every function in the urls package takes a context.Context as its first argument, which tells Laravel where the URL is being built. During an HTTP request, pass r, and generated URLs use the scheme and host that the request arrived with. Outside of a request, such as in a queued job or a console command, pass the ctx that Laravel gave the job or command, and Laravel uses the APP_URL environment variable instead. Make sure to set APP_URL to your application's public URL in production so links sent from background jobs don't point to http://localhost:

ini
APP_URL=https://example.com

URLs for routes ​

You may generate a URL to any of your application's named routes by passing the route's name to urls.Route. Because links name the route rather than repeating its path, every generated URL updates automatically if you change the route's path later.

For example, given a route registered as route.Get("/users/{user}", users.Show).Name("users.show"), a handler may generate the URL for user 1 like this:

go
package users

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

func Store(r *web.Request) *web.Response {
	link, err := urls.Route(r, "users.show", "user", 1) // "http://example.com/users/1"
	if err != nil {
		return web.Fail(err)
	}

	return web.Created(map[string]string{"url": link})
}

urls.Route returns an error when no route has the name or a required parameter is missing. Pass the error to web.Fail, and Laravel responds with a 500 and reports the error.

In a template, pass the route's name and parameters to route instead, such as {{route "users.show" "user" .ID}}. To learn more about generating links in views, check out the templates guide's section on URLs. If you'd like to redirect the user to a route from a handler, return web.RedirectRoute, which accepts the same parameters.

Route parameters ​

Pass a route's parameters after its name, as names and values in pairs. A route without parameters takes only its name. Any parameter whose name doesn't match one of the route's {placeholders} is appended to the URL's query string:

go
urls.Route(r, "home")                                   // "http://example.com"
urls.Route(r, "users.show", "user", 1)                  // "http://example.com/users/1"
urls.Route(r, "comments.show", "post", 1, "comment", 2) // "http://example.com/posts/1/comments/2"

// "http://example.com/users?page=2"
urls.Route(r, "users.index", "page", 2)

// "http://example.com/users/1?tab=posts"
urls.Route(r, "users.show", "user", 1, "tab", "posts")

Sometimes your code decides which parameters to pass as it runs, such as a link that keeps a user's search filter only when they entered one. In that case, build a urls.Params map from each parameter's name to its value, and pass the map in place of the pairs:

go
params := urls.Params{"page": 2}
if filters.Search != "" {
	params["search"] = filters.Search
}

link, err := urls.Route(r, "users.index", params)

To omit trailing optional parameters, leave them out or pass an empty string. Because r.PathValue returns "" for a parameter the request left out, you may forward the values your handler received directly to urls.Route. For a route at /archive/{year?}/{month?}:

go
urls.Route(r, "archive")                            // "http://example.com/archive"
urls.Route(r, "archive", "year", 2026, "month", 10) // "http://example.com/archive/2026/10"

// For a request to /archive/2026: "http://example.com/archive/2026"
urls.Route(r, "archive", "year", r.PathValue("year"), "month", r.PathValue("month"))

Domain parameters ​

When a route is defined inside a domain group, urls.Route builds the URL's host from that domain. You must always pass the domain's parameters explicitly, because Laravel never takes them from the current request. Domain parameters are passed in the same pairs as the path's parameters.

For example, given a route named users.show at /users/{user} inside an {account}.example.com group:

go
// "http://acme.example.com/users/42"
urls.Route(r, "users.show", "account", "acme", "user", 42)

Models and your own types ​

Since you'll often generate links for a model, you may pass the model itself, or a pointer to it, as a route parameter. Laravel fills the parameter with the model's ID, the column its RouteKeyName method returns, or the specific column named in the route's placeholder (such as slug for {post:slug}).

For example, this API handler returns a post along with the URL to its comments:

go
package posts

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

	"app/models"
)

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

	// "http://example.com/posts/42/comments"
	comments, err := urls.Route(r, "posts.comments.index", "post", &post)
	if err != nil {
		return web.Fail(err)
	}

	return web.JSON(map[string]any{
		"title":        post.Title,
		"comments_url": comments,
	})
}

Strings, integers, and UUIDs all work as route parameters out of the box, because Laravel formats each value the way fmt.Sprint does. If you'd like to pass a type of your own, such as a category enum, give the type a String method that returns the text the URL should hold:

go
type Category int

const (
	Engineering Category = iota
	Design
	Product
)

func (c Category) String() string {
	return [...]string{"engineering", "design", "product"}[c]
}

// "http://example.com/articles/engineering"
link, err := urls.Route(r, "articles.category", "category", Engineering)

URLs for paths ​

Sometimes you need an absolute URL for a path that has no named route, such as a static file in your public directory. Pass the path to urls.To, and Laravel prepends your application's scheme and host. If you pass a full URL such as https://laravel.com, urls.To returns it unchanged:

go
import "go.laravel.com/urls"

link := urls.To(r, "/about") // "http://example.com/about"

Package assets ​

A package may serve its own CSS, JavaScript, and images. To generate the URL for one of those files, call view.VendorAsset with the package's asset namespace and the file's path. Laravel appends a hash of the file to the query string so browsers automatically fetch a fresh copy whenever the file changes:

go
// "http://example.com/vendor/inspire/inspire.css?id=34b6aba934cd2bfe"
link := view.VendorAsset(r, "inspire", "inspire.css")

The current URL ​

To read the URL of the incoming request in a handler, call r.FullURL, or read the path from r.URL.Path. To read the last page the user visited, call PreviousURL on the session, which returns "" when the user hasn't visited another page yet:

go
func Show(r *web.Request) *web.Response {
	current := r.FullURL()                // "http://example.com/users?page=2"
	path := r.URL.Path                    // "/users"
	previous := r.Session().PreviousURL() // "http://example.com/dashboard"

	// ...
}

To learn more about building a link to the current page with query parameters added or removed, check out the requests guide's section on request path, host, and method.

Signed URLs ​

Some links act on the user's behalf without asking them to log in, such as an unsubscribe link in a newsletter. Because the route is publicly accessible, you need to verify that nobody tampered with the user ID or other parameters in the URL. A signed URL appends a cryptographic signature hash to the query string so Laravel can detect if any part of the URL has been modified.

To create a signed URL to a route, call urls.SignedRoute, which accepts the same parameters as urls.Route:

go
import "go.laravel.com/urls"

// "http://example.com/unsubscribe/1?signature=…"
link, err := urls.SignedRoute(r, "unsubscribe", "user", 1)

If the link should expire after a period of time, such as a temporary invoice download, use urls.TemporarySignedRoute with how long the link should work. If the link should instead stop working at a specific time, such as a payment link that expires when the invoice falls due, use urls.TemporarySignedRouteUntil with that time:

go
import "time"

download, err := urls.TemporarySignedRoute(r, "invoices.download", 30*time.Minute, "invoice", 42)

payment, err := urls.TemporarySignedRouteUntil(r, "invoices.pay", invoice.DueAt, "invoice", invoice.ID)

Laravel signs URLs using your application's APP_KEY, so signing fails if APP_KEY isn't set. Signed URLs also reserve the signature and expires query parameters, so avoid using those names for your own route or query parameters.

Validating signed route requests ​

To reject requests without a valid signature, assign the ValidateSignature middleware to the route in routes/web.go. It responds with a 403 when the signature is missing, invalid, or expired:

go
import "go.laravel.com/middleware"

route.Get("/unsubscribe/{user}", newsletter.Unsubscribe).
	Name("unsubscribe").
	Middleware(middleware.ValidateSignature{})

If you'd rather verify the signature manually inside a handler, call r.HasValidSignature:

go
func Unsubscribe(r *web.Request) *web.Response {
	if !r.HasValidSignature() {
		return web.Abort(http.StatusForbidden)
	}

	// Unsubscribe the user...

	return web.Redirect("/")
}

警告

The signature covers the URL, not the request body. Read signed values from route parameters with r.PathValue or from the query string with r.Query, never from r.Validate or r.Bind.

Some email providers automatically append tracking parameters, such as utm_source, to links in outgoing emails, which invalidates the signature. To allow specific query parameters on a single route, list them in the Ignore field of ValidateSignature:

go
route.Get("/unsubscribe/{user}", newsletter.Unsubscribe).
	Name("unsubscribe").
	Middleware(middleware.ValidateSignature{Ignore: []string{"utm_source", "utm_campaign"}})

To ignore tracking parameters on every signed URL across your application, list them in the APP_SIGNED_URL_IGNORE environment variable instead. r.HasValidSignature ignores these parameters as well:

ini
APP_SIGNED_URL_IGNORE=utm_source,utm_campaign,fbclid

Because ignored parameters aren't covered by the signature, anyone can modify them, so never trust their values.

If your application runs behind a load balancer that terminates TLS, trust the load balancer. Otherwise every request appears to arrive over http, and a URL signed for https fails its signature check.

Responding to invalid signed routes ​

When someone opens a signed link that has expired or been modified, Laravel responds with a 403 error page that says "This link has expired" or "Invalid signature". The error that the ValidateSignature middleware fails with wraps urls.ErrExpired for a temporary link that has run out, or urls.ErrInvalidSignature for a missing or invalid signature, so errors.Is tells the two apart.

To render a custom response, such as offering to send a fresh link when one expires, write a Render function in the bootstrap package and set it as Render in the Errors option of bootstrap/app.go:

go
package bootstrap

import (
	"errors"
	"net/http"

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

func renderError(r *web.Request, err error) *web.Response {
	if errors.Is(err, urls.ErrExpired) {
		return web.Text("This link has expired. Please request a new one.").
			WithStatus(http.StatusForbidden)
	}

	return nil
}

Returning nil leaves every other error to Laravel.