Head Metadata
- Introduction
- Rendering the head
- Setting defaults
- Metadata for routes
- Metadata for a page
- Open Graph and Twitter
- Icons, hints, and other tags
- Structured data
- Testing the head
Introduction
When someone discovers one of your products in a search result or shares a link in a chat, the title, description, and preview image come from the document's <head>. Because search crawlers and link previews read the initial HTML response before any JavaScript executes, those tags need to be rendered on the server. laravel::head builds document head metadata on the server for both views and Inertia pages.
You describe metadata with a Head value. Your application sets global defaults, routes may add static metadata, and handlers merge request-specific metadata before returning a response. For example, this handler sets a product's title and description from its model fields:
1use laravel::head::{self, Head};2use laravel::prelude::*;3use laravel::view::View;45use crate::models::Product;67pub async fn show(product: Product) -> laravel::Result<View> {8 head::merge(Head::new().title(&product.name).description(&product.summary));910 Ok(view("products.show", data! { product }))11}1use laravel::head::{self, Head};2use laravel::prelude::*;3use laravel::view::View;45use crate::models::Product;67pub async fn show(product: Product) -> laravel::Result<View> {8 head::merge(Head::new().title(&product.name).description(&product.summary));910 Ok(view("products.show", data! { product }))11}
Rendering the head
New applications already render head metadata in Inertia's root view. If you create a layout for server-rendered views, include the head helper there as well.
In views
Call head() inside your layout's <head>, right after static tags such as charset and viewport:
1<!-- resources/views/layouts/app.html -->23<head>4 <meta charset="utf-8">5 <meta name="viewport" content="width=device-width, initial-scale=1">6 {{ head() }}7</head>1<!-- resources/views/layouts/app.html -->23<head>4 <meta charset="utf-8">5 <meta name="viewport" content="width=device-width, initial-scale=1">6 {{ head() }}7</head>
Because the head renders alongside the view, call head::merge before your handler returns. Load your stylesheets and scripts after {{ head() }} with vite(..).
In Inertia pages
Inertia's root view renders the head with {{ inertia_head }} instead of head(). Laravel also includes the page's tags in a head prop so Inertia's client updates the document head as users navigate between pages. New applications enable this with the serverHead option in resources/js/app.tsx:
1createInertiaApp({2 serverHead: true,3 // ...4});1createInertiaApp({2 serverHead: true,3 // ...4});
Leave out Inertia's client-side title callback, because Laravel already applies your title template on the server. Set titles, descriptions, and social tags with head::merge, and reserve Inertia's <Head> component for tags the server doesn't render (if both set <title>, the client overwrites the title after hydration while crawlers still see the server's title).
A partial reload, such as router.reload({ only: ['reviews'] }), omits the head prop so the page keeps its existing head tags while refreshing other props.
Setting defaults
Out of the box, Laravel appends your application's name to every page title, such as About · Laravel. Most applications also want a default description, canonical URL, and social tags on every page. Configure defaults inside with_head in src/app.rs:
1use laravel::head::{Head, OgType, TwitterCard};2use laravel::prelude::*;34Application::configure()5 .with_head(|head, config| {6 head.defaults(7 Head::new()8 .description("Build something great.")9 .canonical()10 .og_type(OgType::Website)11 .og_site_name(&config.app.name)12 .twitter_card(TwitterCard::SummaryLargeImage),13 );14 })1use laravel::head::{Head, OgType, TwitterCard};2use laravel::prelude::*;34Application::configure()5 .with_head(|head, config| {6 head.defaults(7 Head::new()8 .description("Build something great.")9 .canonical()10 .og_type(OgType::Website)11 .og_site_name(&config.app.name)12 .twitter_card(TwitterCard::SummaryLargeImage),13 );14 })
canonical() outputs a <link rel="canonical"> tag for the current URL without its query string, so /products?utm_source=news and /products share one canonical URL. To preserve specific query parameters such as pagination, use canonical_with_query(["page"]). To point at a different URL altogether, use canonical_url("/products/1").
Titles
Page titles are formatted through a title template where %s is replaced by the page's title. By default, the template is %s · {app name}, so title("About") renders About · Laravel. Pages without a title render your application's name alone, and a title(...) set in global defaults renders as written without the template.
To customize the template globally or for a route group (such as an admin area), call title_template. To bypass the template on a single page, use exact_title:
1Head::new().title_template("%s | Laravel News")23Head::new().exact_title("Laravel | The Rust Web Framework")1Head::new().title_template("%s | Laravel News")23Head::new().exact_title("Laravel | The Rust Web Framework")
Error pages
By default, every error page uses its HTTP status reason as its title, such as Not Found · Laravel. Since search engines shouldn't index error pages (and a 404 page benefits from a clearer description), configure error metadata inside with_head using errors for all error pages and error for a specific status code:
1use laravel::head::{Head, Robots};2use laravel::prelude::*;34Application::configure()5 .with_head(|head, _| {6 head.errors(Head::new().robots([Robots::NoIndex, Robots::Follow]));78 head.error(9 404,10 Head::new().description("The page you are looking for could not be found."),11 );12 })1use laravel::head::{Head, Robots};2use laravel::prelude::*;34Application::configure()5 .with_head(|head, _| {6 head.errors(Head::new().robots([Robots::NoIndex, Robots::Follow]));78 head.error(9 404,10 Head::new().description("The page you are looking for could not be found."),11 );12 })
Error metadata overrides any route or handler metadata and applies to error views, the Inertia error page, and custom renderers. Error pages omit the canonical link unless your error metadata sets one explicitly.
Metadata for routes
When a page's metadata is static, such as a contact page's title or a robots rule for an entire admin area, attach a Head directly to a route, route group, or resource route with with_head:
1use laravel::head::{Head, Robots};2use laravel::prelude::*;34pub fn routes(route: &mut Router) {5 route6 .view("/contact", "contact")7 .with_head(Head::new().title("Contact Us").description("Get in touch."));89 route10 .with_head(Head::new().robots(Robots::None))11 .prefix("/admin")12 .group(|route| {13 route14 .get("/dashboard", admin::dashboard)15 .with_head(Head::new().title("Dashboard"));16 });17}1use laravel::head::{Head, Robots};2use laravel::prelude::*;34pub fn routes(route: &mut Router) {5 route6 .view("/contact", "contact")7 .with_head(Head::new().title("Contact Us").description("Get in touch."));89 route10 .with_head(Head::new().robots(Robots::None))11 .prefix("/admin")12 .group(|route| {13 route14 .get("/dashboard", admin::dashboard)15 .with_head(Head::new().title("Dashboard"));16 });17}
When nested groups or a route set the same tag, Laravel uses the most specific value: the route's metadata overrides its group's, and an inner group's metadata overrides an outer group's.
Metadata for a page
Most metadata depends on the current request, such as the name and photo of a specific product. Call head::merge in a handler or middleware before the response renders. You may call head::merge multiple times during a request, and later calls override earlier ones.
For example, this handler sets a product's Open Graph image from its image_url and image_alt columns, and hides unpublished drafts from search engines:
1use laravel::head::{self, Head, OgImage, OgType};2use laravel::prelude::*;3use laravel::view::View;45use crate::models::Product;67pub async fn show(product: Product) -> laravel::Result<View> {8 head::merge(9 Head::new()10 .title(&product.name)11 .og_type(OgType::Website)12 .og_image(13 OgImage::new(&product.image_url)14 .alt(&product.image_alt)15 .size(1200, 630),16 ),17 );1819 if product.published_at.is_none() {20 head::merge(Head::new().hidden_from_robots());21 }2223 Ok(view("products.show", data! { product }))24}1use laravel::head::{self, Head, OgImage, OgType};2use laravel::prelude::*;3use laravel::view::View;45use crate::models::Product;67pub async fn show(product: Product) -> laravel::Result<View> {8 head::merge(9 Head::new()10 .title(&product.name)11 .og_type(OgType::Website)12 .og_image(13 OgImage::new(&product.image_url)14 .alt(&product.image_alt)15 .size(1200, 630),16 ),17 );1819 if product.published_at.is_none() {20 head::merge(Head::new().hidden_from_robots());21 }2223 Ok(view("products.show", data! { product }))24}
Because head::merge accepts anything that implements Into<Head>, you may implement From<&Product> for Head next to your model and pass a reference to the model directly in your handler:
1use laravel::head::Head;23impl From<&Product> for Head {4 fn from(product: &Product) -> Self {5 Head::new().title(&product.name).description(&product.summary)6 }7}1use laravel::head::Head;23impl From<&Product> for Head {4 fn from(product: &Product) -> Self {5 Head::new().title(&product.name).description(&product.summary)6 }7}
1pub async fn show(product: Product) -> laravel::Result<View> {2 head::merge(&product);34 Ok(view("products.show", data! { product }))5}1pub async fn show(product: Product) -> laravel::Result<View> {2 head::merge(&product);34 Ok(view("products.show", data! { product }))5}
How layers combine
Laravel merges metadata from five layers, from lowest priority to highest:
- Your application's name, used as the fallback title.
- Global defaults registered with
head.defaults(...)insrc/app.rs. - Metadata attached to route groups, followed by metadata attached directly to the route.
- Each
head::merge(...)call made during the request, in the order called. - On error responses, the HTTP status reason as the title, followed by
head.errors(...)andhead.error(status, ...).
For single-value tags such as title or description, the highest layer takes precedence while lower layers retain their other tags (so a route's description stays intact when a handler only sets the title). Repeatable tags such as alternate languages are combined unless a higher layer defines the same entry again. A page's Open Graph images, videos, or audio files replace those from the global defaults so a product's photo isn't rendered alongside your site's default social image.
Open Graph and Twitter
When someone shares a link on social media or in a chat app, link previews read the page's Open Graph and Twitter Card tags. With the global defaults configured earlier, calling head::merge in the /products/1 handler:
1use laravel::head::{self, Head, OgImage};23head::merge(4 Head::new()5 .title("Trail Running Shoes")6 .description("Lightweight waterproof shoes built for mountain trails.")7 .og_image(OgImage::new("/images/shoes.jpg").alt("Trail Running Shoes")),8);1use laravel::head::{self, Head, OgImage};23head::merge(4 Head::new()5 .title("Trail Running Shoes")6 .description("Lightweight waterproof shoes built for mountain trails.")7 .og_image(OgImage::new("/images/shoes.jpg").alt("Trail Running Shoes")),8);
produces the following tags in the document's <head>:
1<title>Trail Running Shoes · Laravel</title>2<meta name="description" content="Lightweight waterproof shoes built for mountain trails.">3<link rel="canonical" href="https://example.com/products/1">4<meta property="og:type" content="website">5<meta property="og:site_name" content="Laravel">6<meta property="og:title" content="Trail Running Shoes · Laravel">7<meta property="og:description" content="Lightweight waterproof shoes built for mountain trails.">8<meta property="og:image" content="https://example.com/images/shoes.jpg">9<meta property="og:image:alt" content="Trail Running Shoes">10<meta name="twitter:card" content="summary_large_image">11<meta name="twitter:title" content="Trail Running Shoes · Laravel">12<meta name="twitter:description" content="Lightweight waterproof shoes built for mountain trails.">13<meta name="twitter:image" content="https://example.com/images/shoes.jpg">14<meta name="twitter:image:alt" content="Trail Running Shoes">1<title>Trail Running Shoes · Laravel</title>2<meta name="description" content="Lightweight waterproof shoes built for mountain trails.">3<link rel="canonical" href="https://example.com/products/1">4<meta property="og:type" content="website">5<meta property="og:site_name" content="Laravel">6<meta property="og:title" content="Trail Running Shoes · Laravel">7<meta property="og:description" content="Lightweight waterproof shoes built for mountain trails.">8<meta property="og:image" content="https://example.com/images/shoes.jpg">9<meta property="og:image:alt" content="Trail Running Shoes">10<meta name="twitter:card" content="summary_large_image">11<meta name="twitter:title" content="Trail Running Shoes · Laravel">12<meta name="twitter:description" content="Lightweight waterproof shoes built for mountain trails.">13<meta name="twitter:image" content="https://example.com/images/shoes.jpg">14<meta name="twitter:image:alt" content="Trail Running Shoes">
Once a page has any Open Graph tag, og:title and og:description fall back to the page's title and description automatically. Similarly, once a page has a Twitter tag (such as the default card), Twitter tags fall back to the Open Graph values. Any value you set explicitly with og_title, og_description, twitter_title, twitter_description, or twitter_image always takes precedence over these fallbacks.
Relative image paths such as /images/shoes.jpg are automatically expanded to absolute URLs, since social crawlers require full URLs.
Icons, hints, and other tags
Browsers also read <head> for favicons, theme colors, resource preloads, and RSS or Atom feeds. Most applications configure these once in head.defaults(...) inside with_head:
1use laravel::head::{Feed, Head, Icon, ImageType, Link, Media, Preload};23head.defaults(4 Head::new()5 .theme_color("#ffffff")6 .theme_color_for(Media::Dark, "#111827")7 .icon(Icon::new("/favicon.svg").mime(ImageType::Svg))8 .apple_touch_icon(Icon::new("/apple-touch-icon.png").sizes("180x180"))9 .manifest("/site.webmanifest")10 .preconnect("https://fonts.bunny.net")11 .preload("/fonts/inter.woff2", Preload::Font)12 .alternate("fr", "https://example.com/fr/about")13 .feed(Feed::atom("/feed.atom").title("Laravel Atom"))14 .meta("format-detection", "telephone=no")15 .link(16 Link::new("search", "/opensearch.xml")17 .attr("type", "application/opensearchdescription+xml"),18 ),19);1use laravel::head::{Feed, Head, Icon, ImageType, Link, Media, Preload};23head.defaults(4 Head::new()5 .theme_color("#ffffff")6 .theme_color_for(Media::Dark, "#111827")7 .icon(Icon::new("/favicon.svg").mime(ImageType::Svg))8 .apple_touch_icon(Icon::new("/apple-touch-icon.png").sizes("180x180"))9 .manifest("/site.webmanifest")10 .preconnect("https://fonts.bunny.net")11 .preload("/fonts/inter.woff2", Preload::Font)12 .alternate("fr", "https://example.com/fr/about")13 .feed(Feed::atom("/feed.atom").title("Laravel Atom"))14 .meta("format-detection", "telephone=no")15 .link(16 Link::new("search", "/opensearch.xml")17 .attr("type", "application/opensearchdescription+xml"),18 ),19);
For any tag without a dedicated helper method, use meta or link as shown in the last two lines.
On paginated pages, pass your paginator to paginated. It keeps the paginator's page parameter (such as page or cursor) in the canonical URL and emits <link rel="prev"> and <link rel="next"> tags when neighboring pages exist:
1use laravel::head::{self, Head};2use laravel::prelude::*;3use laravel::view::View;45use crate::models::Product;67pub async fn index() -> laravel::Result<View> {8 let products = Product::query().order_by(Product::id).paginate(15).await?;910 head::merge(Head::new().paginated(&products));1112 Ok(view("products.index", data! { products }))13}1use laravel::head::{self, Head};2use laravel::prelude::*;3use laravel::view::View;45use crate::models::Product;67pub async fn index() -> laravel::Result<View> {8 let products = Product::query().order_by(Product::id).paginate(15).await?;910 head::merge(Head::new().paginated(&products));1112 Ok(view("products.index", data! { products }))13}
If you build pagination links by hand instead of using a paginator, set canonical_with_query(["page"]), prev_page, and next_page directly.
Structured data
Search engines read JSON-LD structured data to display rich results, such as a product's price and stock status next to its search listing. Call schema on a Head to emit JSON-LD scripts. The laravel::head::schema module includes builders for Article, BlogPosting, Product, Offer, Brand, Breadcrumbs, Faq, Organization, Person, WebPage, and WebSite:
1use laravel::head::schema::{Availability, Breadcrumbs, Offer, Product};2use laravel::head::{self, Head};34head::merge(5 Head::new()6 .schema(7 Product::new().name("Running shoes").offers(8 Offer::new()9 .price(49.99)10 .currency("USD")11 .availability(Availability::InStock),12 ),13 )14 .schema(15 Breadcrumbs::new()16 .item("Home", "https://example.com")17 .item("Shop", "https://example.com/shop"),18 ),19);1use laravel::head::schema::{Availability, Breadcrumbs, Offer, Product};2use laravel::head::{self, Head};34head::merge(5 Head::new()6 .schema(7 Product::new().name("Running shoes").offers(8 Offer::new()9 .price(49.99)10 .currency("USD")11 .availability(Availability::InStock),12 ),13 )14 .schema(15 Breadcrumbs::new()16 .item("Home", "https://example.com")17 .item("Shop", "https://example.com/shop"),18 ),19);
For any other schema.org type, build it dynamically with Thing, such as Thing::new("Recipe").set("name", "Pancakes"). If you reuse a custom schema type across your application, implement Schema for a Serialize struct:
1use laravel::head::schema::Schema;23#[derive(Serialize)]4#[serde(rename_all = "camelCase")]5struct JobPosting {6 title: String,7}89impl Schema for JobPosting {10 fn schema_type(&self) -> &str {11 "JobPosting"12 }13}1use laravel::head::schema::Schema;23#[derive(Serialize)]4#[serde(rename_all = "camelCase")]5struct JobPosting {6 title: String,7}89impl Schema for JobPosting {10 fn schema_type(&self) -> &str {11 "JobPosting"12 }13}
Omit empty fields rather than passing empty strings or None. In debug mode, a schema containing an empty value fails to render and reports the offending field path; in production, Laravel logs a warning and omits the schema.
Testing the head
In your HTTP tests, call assert_head() on a response to inspect either the <head> of an HTML view or the head prop of an Inertia page with the same assertions:
1use laravel::testing::prelude::*;23#[laravel::test]4async fn product_pages_have_social_tags(app: Application) {5 app.get("/products/1")6 .await7 .assert_head()8 .title("Trail Running Shoes · Laravel")9 .meta("og:title", "Trail Running Shoes · Laravel")10 .link("canonical", "http://localhost/products/1")11 .schema("Product")12 .missing("robots");13}1use laravel::testing::prelude::*;23#[laravel::test]4async fn product_pages_have_social_tags(app: Application) {5 app.get("/products/1")6 .await7 .assert_head()8 .title("Trail Running Shoes · Laravel")9 .meta("og:title", "Trail Running Shoes · Laravel")10 .link("canonical", "http://localhost/products/1")11 .schema("Product")12 .missing("robots");13}
| Assertion | What it checks |
|---|---|
title(text) |
That the head contains a single <title> with the given text. |
meta(name, |
That a <meta> tag with the given name or property has the expected content. |
link(rel, |
That a <link> tag has the given rel and URL. |
schema(type) |
That a JSON-LD schema has the given @type, such as Product. |
has(key), missing(key) |
That a tag matching the key exists or is absent (such as robots, og:title, or canonical). |
To verify that a partial reload omits the head prop, reload the page and assert missing("head"):
1#[laravel::test]2async fn reviews_reload_without_the_head(app: Application) {3 app.get("/products/1")4 .await5 .assert_inertia()6 .reload_only(&["reviews"])7 .await8 .missing("head");9}1#[laravel::test]2async fn reviews_reload_without_the_head(app: Application) {3 app.get("/products/1")4 .await5 .assert_inertia()6 .reload_only(&["reviews"])7 .await8 .missing("head");9}