Skip to content

URL Generation

The Basics

URL Generation

Introduction

The laravel::url module provides helpers for generating absolute URLs to your application's routes, paths, and package assets. 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, laravel::url 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

During an HTTP request, 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, 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:

1APP_URL=https://example.com
1APP_URL=https://example.com

URLs for routes

You may generate a URL to any of your application's routes by passing its handler function to route! (available in the prelude). Because links reference the handler directly, every generated URL updates automatically if you change the route's URI, and renaming or removing a handler produces a compile-time error instead of a broken link.

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

1use laravel::prelude::*;
2 
3let url = route!(users::show, 1)?; // "http://example.com/users/1"
1use laravel::prelude::*;
2 
3let url = route!(users::show, 1)?; // "http://example.com/users/1"

route! returns a laravel::Result because the handler might not be registered on a route, or a required parameter might be missing. In a handler, ? turns that failure into an error response. When you need a function rather than a macro, such as inside generic code, call url::route(handler, params) directly.

In a template, pass the handler's path as a string instead, such as {{ route("users::show", user) }}. 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 redirect!, which accepts the same parameters.

Route parameters

When a route has no parameters, pass its handler alone. For routes with {placeholders}, pass positional arguments in order:

1route!(home::show)?; // "http://example.com"
2route!(users::show, 1)?; // "http://example.com/users/1"
3route!(comments::show, 1, 2)?; // "http://example.com/posts/1/comments/2"
1route!(home::show)?; // "http://example.com"
2route!(users::show, 1)?; // "http://example.com/users/1"
3route!(comments::show, 1, 2)?; // "http://example.com/posts/1/comments/2"

You may also pass parameters by name with key = value. Named parameters may mix models, numbers, and strings in the same call, and any named parameter that doesn't match a route placeholder is appended to the URL's query string:

1// "http://example.com/users?page=2"
2route!(users::index, page = 2)?;
3 
4// "http://example.com/users/1?tab=posts"
5route!(users::show, user = 1, tab = "posts")?;
1// "http://example.com/users?page=2"
2route!(users::index, page = 2)?;
3 
4// "http://example.com/users/1?tab=posts"
5route!(users::show, user = 1, tab = "posts")?;

For query parameter names that aren't Rust identifiers, quote the key, such as route!(users::index, "utm-source" = "newsletter")?.

To omit trailing optional parameters, leave them out or pass None. Passing None lets you forward Option values that your handler received directly to route!. For a route at /archive/{year?}/{month?}:

1route!(archive::show)?; // "http://example.com/archive"
2route!(archive::show, 2026, 10)?; // "http://example.com/archive/2026/10"
3route!(archive::show, 2026, None::<u8>)?; // "http://example.com/archive/2026"
1route!(archive::show)?; // "http://example.com/archive"
2route!(archive::show, 2026, 10)?; // "http://example.com/archive/2026/10"
3route!(archive::show, 2026, None::<u8>)?; // "http://example.com/archive/2026"

Domain parameters

When a route is defined inside a domain group, route! builds the URL's host from that domain. You must always pass the domain's parameters explicitly, because Laravel never infers them from the current request. Positional parameters fill the domain placeholders first, followed by the path placeholders.

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

1// "http://acme.example.com/users/42"
2route!(users::show, "acme", 42)?;
3 
4// "http://acme.example.com/users/42"
5route!(users::show, account = "acme", user = 42)?;
1// "http://acme.example.com/users/42"
2route!(users::show, "acme", 42)?;
3 
4// "http://acme.example.com/users/42"
5route!(users::show, account = "acme", user = 42)?;

Models and your own types

Since you'll often generate links for a model, you may pass a reference to the model itself as a route parameter. Laravel automatically extracts the model's primary key, its custom route_key, 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:

1use laravel::prelude::*;
2use serde_json::{Value, json};
3 
4use crate::models::Post;
5 
6pub async fn show(post: Post) -> laravel::Result<Json<Value>> {
7 Ok(Json(json!({
8 "title": post.title,
9 // "http://example.com/posts/42/comments"
10 "comments_url": route!(comments::index, &post)?,
11 })))
12}
1use laravel::prelude::*;
2use serde_json::{Value, json};
3 
4use crate::models::Post;
5 
6pub async fn show(post: Post) -> laravel::Result<Json<Value>> {
7 Ok(Json(json!({
8 "title": post.title,
9 // "http://example.com/posts/42/comments"
10 "comments_url": route!(comments::index, &post)?,
11 })))
12}

Strings, integers, UUIDs, and ULIDs all work as route parameters out of the box. If you'd like to pass a custom type of your own, such as an enum, implement the RouteParam trait:

1use laravel::prelude::*;
2use laravel::url::RouteParam;
3 
4pub enum Category {
5 Engineering,
6 Design,
7 Product,
8}
9 
10impl RouteParam for Category {
11 fn to_route_param(&self) -> String {
12 match self {
13 Self::Engineering => "engineering",
14 Self::Design => "design",
15 Self::Product => "product",
16 }
17 .to_owned()
18 }
19}
20 
21// "http://example.com/articles/engineering"
22let url = route!(articles::by_category, Category::Engineering)?;
1use laravel::prelude::*;
2use laravel::url::RouteParam;
3 
4pub enum Category {
5 Engineering,
6 Design,
7 Product,
8}
9 
10impl RouteParam for Category {
11 fn to_route_param(&self) -> String {
12 match self {
13 Self::Engineering => "engineering",
14 Self::Design => "design",
15 Self::Product => "product",
16 }
17 .to_owned()
18 }
19}
20 
21// "http://example.com/articles/engineering"
22let url = route!(articles::by_category, Category::Engineering)?;

URLs for paths

Sometimes you need an absolute URL for a path that isn't backed by a route handler, such as a static file in your public directory. Pass the path to url::to, and Laravel prepends your application's scheme and host. If you pass a full URL such as https://laravel.com, url::to returns it unchanged:

1use laravel::url;
2 
3let url = url::to("/about"); // "http://example.com/about"
1use laravel::url;
2 
3let url = url::to("/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 url::vendor_asset 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:

1// "http://example.com/vendor/inspire/inspire.css?id=34b6aba934cd2bfe"
2let url = url::vendor_asset("inspire", "inspire.css");
1// "http://example.com/vendor/inspire/inspire.css?id=34b6aba934cd2bfe"
2let url = url::vendor_asset("inspire", "inspire.css");

The current URL

To read the URL of the incoming request in a handler, call url or full_url on the Request. To read the last page the user visited, call previous_url on the session:

1use laravel::prelude::*;
2 
3pub async fn show(request: Request) -> laravel::Result<String> {
4 let current = request.url(); // "http://example.com/users"
5 let with_query = request.full_url(); // "http://example.com/users?page=2"
6 let previous = request.session()?.previous_url(); // Some("http://example.com/dashboard")
7 
8 // ...
9}
1use laravel::prelude::*;
2 
3pub async fn show(request: Request) -> laravel::Result<String> {
4 let current = request.url(); // "http://example.com/users"
5 let with_query = request.full_url(); // "http://example.com/users?page=2"
6 let previous = request.session()?.previous_url(); // Some("http://example.com/dashboard")
7 
8 // ...
9}

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 url::signed_route, which accepts the same parameters as url::route:

1use laravel::url;
2 
3// "http://example.com/unsubscribe/1?signature=…"
4let url = url::signed_route(newsletter::unsubscribe, 1)?;
1use laravel::url;
2 
3// "http://example.com/unsubscribe/1?signature=…"
4let url = url::signed_route(newsletter::unsubscribe, 1)?;

If the link should expire after a period of time, such as a temporary invoice download, use url::temporary_signed_route. Pass a duration from now (such as 30.minutes()) or a specific moment when the link should stop working:

1use laravel::prelude::*;
2use laravel::url;
3 
4let url = url::temporary_signed_route(invoices::download, 30.minutes(), 42)?;
1use laravel::prelude::*;
2use laravel::url;
3 
4let url = url::temporary_signed_route(invoices::download, 30.minutes(), 42)?;

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 your route file. It responds with a 403 when the signature is missing, invalid, or expired:

1use laravel::http::middleware::ValidateSignature;
2 
3route
4 .get("/unsubscribe/{user}", newsletter::unsubscribe)
5 .middleware(ValidateSignature);
1use laravel::http::middleware::ValidateSignature;
2 
3route
4 .get("/unsubscribe/{user}", newsletter::unsubscribe)
5 .middleware(ValidateSignature);

If you'd rather verify the signature manually inside a handler, call has_valid_signature on the Request:

1use laravel::prelude::*;
2 
3pub async fn unsubscribe(request: Request) -> laravel::Result<Redirect> {
4 laravel::abort_unless(request.has_valid_signature(), 403)?;
5 
6 // Unsubscribe the user...
7 
8 Ok(Redirect::to("/"))
9}
1use laravel::prelude::*;
2 
3pub async fn unsubscribe(request: Request) -> laravel::Result<Redirect> {
4 laravel::abort_unless(request.has_valid_signature(), 403)?;
5 
6 // Unsubscribe the user...
7 
8 Ok(Redirect::to("/"))
9}

The signature covers the URL, not the request body. Read signed values from route parameters, or from the query string with Query<T> or request.query(), never from Valid<T> or request.parse().

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, pass them to ValidateSignature::ignore(...):

1route
2 .get("/unsubscribe/{user}", newsletter::unsubscribe)
3 .middleware(ValidateSignature::ignore(["utm_source", "utm_campaign"]));
1route
2 .get("/unsubscribe/{user}", newsletter::unsubscribe)
3 .middleware(ValidateSignature::ignore(["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. request.has_valid_signature() ignores these parameters as well:

1APP_SIGNED_URL_IGNORE=utm_source,utm_campaign,fbclid
1APP_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 generic 403 error page. The underlying error is an InvalidSignature, which distinguishes between InvalidSignature::Expired for a temporary link that has run out and InvalidSignature::Incorrect for a missing or invalid signature.

To render a custom response, such as offering to send a fresh link when one expires, register an error renderer in src/app.rs:

1use laravel::url::InvalidSignature;
2 
3.with_errors(|errors, _| {
4 errors.render(|invalid: &InvalidSignature, _request, status| {
5 if *invalid == InvalidSignature::Expired {
6 return Some((status, "This link has expired. Please request a new one."));
7 }
8 
9 None
10 });
11})
1use laravel::url::InvalidSignature;
2 
3.with_errors(|errors, _| {
4 errors.render(|invalid: &InvalidSignature, _request, status| {
5 if *invalid == InvalidSignature::Expired {
6 return Some((status, "This link has expired. Please request a new one."));
7 }
8 
9 None
10 });
11})