> ## Documentation Index
> Fetch the complete documentation index at: https://kawax.biz/llms.txt
> Use this file to discover all available pages before exploring further.

# Laravel Head — document <head> 管理套件

> 介紹 laravel/head。以流暢式 API 跨 Blade、Livewire、Inertia 管理 title、meta、Open Graph、canonical URL、robots、效能提示、結構化資料的 Laravel 官方套件。2026 年 7 月 28 日發佈。

## 前言

[laravel/head](https://github.com/laravel/head) 是以流暢式 API 管理應用文件 `<head>` 的 Laravel 官方套件。支援 title、meta 標籤、Open Graph、canonical URL、robots 指令、效能提示、結構化資料，可在 Blade、Livewire、Inertia 中運作。2026 年 7 月 28 日發佈 v0.1.0。

```bash theme={null}
composer require laravel/head
```

## 解析優先順序

頁面的 head 資料由優先度低到高分為以下 5 層解析：

1. 頁面預設值
2. 路由群組中繼資料
3. 路由中繼資料
4. 執行時中繼資料
5. 錯誤頁面中繼資料

上層會以欄位為單位覆寫下層。例如執行時設定的 title 會取代路由的 title，但不會取代 description。

```mermaid theme={null}
graph TD
    A["頁面預設值"] --> B["路由群組<br>中繼資料"]
    B --> C["路由中繼資料"]
    C --> D["執行時中繼資料"]
    D --> E["錯誤頁面<br>中繼資料"]
    E --> F["最終的<br>&lt;head&gt; 輸出"]
```

## 註冊預設值

在 Service Provider 註冊整站預設值。

```php theme={null}
use Laravel\Head\Facades\Head;
use Laravel\Head\HeadBuilder;
use Laravel\Head\Enums\OgType;

Head::defaults(function (HeadBuilder $head) {
    $head
        ->title('Acme', suffix: ' - Acme')
        ->description('Build something great.')
        ->canonical()
        ->og(siteName: 'Acme', type: OgType::Website)
        ->searchableByRobots()
        ->preconnect('https://fonts.example.com');
});
```

預設層是優先度最低的頁面層。除非上層設定了 title 否則會顯示 `Acme`，若上層設定了 title，繼承的 suffix 也會套用（`Head::title('About')` 會變成 `About - Acme`）。

## 路由中繼資料

靜態頁面可直接把中繼資料附掛到路由定義。

```php theme={null}
Route::view('/contact', 'contact')
    ->name('contact')
    ->withHead(
        title: 'Contact Us',
        description: 'Get in touch.',
    );
```

也可以套用共通中繼資料到整個群組。

```php theme={null}
Route::withHead(robots: 'noindex, nofollow')
    ->prefix('admin')
    ->name('admin.')
    ->group(function () {
        Route::get('/dashboard', DashboardController::class)
            ->name('dashboard')
            ->withHead(title: 'Dashboard');
    });
```

`withHead()` 會透過 Laravel 標準的路由中繼資料 API（`->metadata()` 的 `head` key 下）以純陣列保存，因此與路由快取相容。

## 執行時中繼資料

像文章標題那樣要等到請求進來才知道的值，可用 `Head` Facade 在執行時設定。

```php theme={null}
use App\Models\Post;
use Laravel\Head\Facades\Head;

public function show(Post $post)
{
    Head::title($post->title)
        ->description($post->description);

    return view('posts.show', ['post' => $post]);
}
```

條件式中繼資料可用 `when()` / `unless()` 流暢寫出。

```php theme={null}
Head::title($post->title)
    ->when($post->isDraft(), fn ($head) => $head->hiddenFromRobots());
```

## 錯誤頁面

也能依狀態碼註冊中繼資料。

```php theme={null}
use Laravel\Head\ErrorPages;
use Laravel\Head\Facades\Head;

Head::errors(function (ErrorPages $errors) {
    $errors->defaults(robots: 'noindex, follow');

    $errors->status(404,
        title: 'Page Not Found',
        description: 'The page you are looking for could not be found.',
    );
});
```

已註冊的錯誤狀態被繪製時，這些中繼資料會優先於其他任何層。

## Open Graph 與 Twitter Card

可用 `og()` 設定 Open Graph 屬性，並用 `ogImage()` 等方法加入影像、影片、音訊。

```php theme={null}
use Laravel\Head\Enums\ImageType;
use Laravel\Head\Enums\OgType;

Head::og(type: OgType::Article, title: $post->title)
    ->ogImage($post->hero_image_url)
    ->ogImage(
        $post->gallery_image_url,
        alt: $post->gallery_image_alt,
        width: 1200,
        height: 630,
        type: ImageType::Jpeg,
    );
```

document 的 `title` 與 `description` 會自動補上未設定的 `og:title` / `og:description`。

Twitter Card 只要在預設值註冊，就會自動用與 Open Graph 相同的 title、description、影像繪製。

```php theme={null}
use Laravel\Head\Enums\TwitterCard;
use Laravel\Head\Facades\Head;
use Laravel\Head\HeadBuilder;

Head::defaults(fn (HeadBuilder $head) => $head->twitter(
    card: TwitterCard::SummaryWithLargeImage,
));
```

也可在個別頁面明確覆寫 Twitter 的值。

```php theme={null}
Head::twitter(title: $post->social_title)
    ->twitterImage($post->social_image_url, alt: $post->title);
```

## PWA、效能與 icon

`pwa()` helper 可一次設定可安裝 Web 應用所需的 `<head>` 標籤。

```php theme={null}
Head::pwa(
    name: 'Acme',
    manifest: '/site.webmanifest',
    themeColor: '#0f172a',
    appleTouchIcon: '/apple-touch-icon.png',
    appleWebAppStatusBarStyle: 'black',
);
```

## 主題色

主題色可在全域、路由、執行時任一層設定。使用 `Media` enum 可為不同媒體指定主題色。

```php theme={null}
use Laravel\Head\Enums\Media;

Head::themeColor('#ffffff', media: Media::Light)
    ->themeColor('#111827', media: Media::Dark);
```

`Media` 也包含 `Portrait` 與 `Landscape`。

## 應用中繼資料與 icon

Laravel Head 內含瀏覽器與應用一般中繼資料的 helper。

```php theme={null}
use Laravel\Head\Enums\ImageType;
use Laravel\Head\Enums\Media;

Head::applicationName('Acme')
    ->colorScheme('light dark')
    ->referrer('strict-origin-when-cross-origin')
    ->viewport('width=device-width, initial-scale=1')
    ->appleWebAppTitle('Acme')
    ->webAppCapable()
    ->appleWebAppStatusBarStyle('black')
    ->favicon('/favicon.svg', type: ImageType::Svg)
    ->icon('/favicon-32x32.png', type: ImageType::Png, sizes: '32x32')
    ->appleTouchIcon('/apple-touch-icon.png', sizes: '180x180')
    ->appleTouchStartupImage('/launch.png', media: Media::Portrait)
    ->maskIcon('/safari-pinned-tab.svg', color: '#111827')
    ->manifest('/site.webmanifest');
```

`favicon()` 是 `icon()` 的別名，接受相同的 `type`、`sizes`、`media` 參數。

## 效能與可發現性

Laravel Head 也能繪製效能提示、分頁連結、語系替代、Feed 發現用標籤。

```php theme={null}
Head::preload(asset('fonts/inter.woff2'), as: 'font', crossorigin: true)
    ->prefetch(asset('images/next.webp'))
    ->preconnect('https://cdn.example.com')
    ->dnsPrefetch('https://analytics.example.com')
    ->paginate($posts)
    ->alternates([
        'en' => 'https://example.com/en/about',
        'fr' => 'https://example.com/fr/about',
        'x-default' => 'https://example.com/about',
    ])
    ->feed('/feed', title: 'Acme RSS')
    ->feed('/feed.atom', type: 'atom', title: 'Acme Atom');
```

`preloadAsset()` / `prefetchAsset()` 會以 `asset()` helper 解析 URL，並依副檔名自動判斷 `as` 屬性。

```php theme={null}
Head::preloadAsset('fonts/inter.woff2')
    ->prefetchAsset('images/next.webp');
```

```html theme={null}
<link rel="preload" href="https://example.com/fonts/inter.woff2" as="font" crossorigin>
<link rel="prefetch" href="https://example.com/images/next.webp" as="image">
```

## 自訂標籤

沒有專屬方法的標籤可用 `meta()` / `link()` 加入。

```php theme={null}
Head::meta('format-detection', 'telephone=no')
    ->meta('article:author', $post->author->name)
    ->link('search', '/opensearch.xml', [
        'type' => 'application/opensearchdescription+xml',
        'title' => 'Acme Search',
    ]);
```

`meta()` 對一般 meta 標籤使用 `name=`，若鍵值原本應使用 `property=`（如 Open Graph `og:` 或 article 中繼資料 `article:`），會自動切換。

```php theme={null}
Head::meta('description', 'About Acme')
    ->meta('og:title', 'About Acme');
```

```html theme={null}
<meta name="description" content="About Acme">
<meta property="og:title" content="About Acme">
```

## 結構化資料（JSON-LD）

內建的 schema builder 涵蓋主要 JSON-LD 類型。

```php theme={null}
use Laravel\Head\Enums\OfferAvailability;
use Laravel\Head\Facades\Schema;

Head::schema(
    Schema::product()
        ->name($product->name)
        ->offers(
            Schema::offer()
                ->price($product->price)
                ->currency('USD')
                ->availability(OfferAvailability::InStock)
        )
);
```

內建的 factory 方法包括 `article`、`blogPosting`、`product`、`offer`、`brand`、`breadcrumbs`、`faq`、`organization`、`person`、`webPage`、`webSite`。未定義的 factory 方法會回退到通用的 schema 物件，因此也能表達自訂 schema.org 類型。

麵包屑項目可逐一或一次加入，位置會依加入順序自動指定。

```php theme={null}
Head::schema(
    Schema::breadcrumbs()->items([
        'Home' => route('home'),
        'Shop' => route('shop.index'),
        'Shoes' => route('shop.category', 'shoes'),
    ])
);
```

FAQ 問題也是相同模式。可用 `question()` 逐一加入或用 `questions()` 一次加入。

```php theme={null}
Head::schema(
    Schema::faq()->questions([
        'What is Laravel Head?' => 'A fluent API for managing the document head.',
        'Is it free?' => 'Yes, it is open source.',
    ])
);
```

自訂 schema 類型可明確註冊。

```php theme={null}
use DateTimeInterface;
use Laravel\Head\Facades\Schema;
use Laravel\Head\Schema\SchemaObject;
use Laravel\Head\SchemaType;

#[SchemaType('JobPosting')]
class JobPosting extends SchemaObject
{
    public function title(string $title): static
    {
        return $this->set('title', $title);
    }

    public function datePosted(DateTimeInterface|string $date): static
    {
        return $this->date('datePosted', $date);
    }
}

Schema::register(JobPosting::class);
```

## 總結

`laravel/head` 能跨 Blade、Livewire、Inertia 統一管理 SEO 與社交分享所需的中繼資料。透過預設、路由、執行時、錯誤頁面的 5 層架構，可保持整站一致，也能對每個頁面做彈性客製。

<Card title="laravel/head 儲存庫" icon="github" href="https://github.com/laravel/head">
  原始碼與最新資訊請見此處。
</Card>


## Related topics

- [Google Sheets API for Laravel](/zh-TW/packages/laravel-google-sheets/index.md)
- [套件的 CHANGELOG 與發布管理](/zh-TW/advanced/package-changelog.md)
- [套件的靜態分析（PHPStan / Larastan）](/zh-TW/advanced/package-static-analysis.md)
- [套件的版本相容性管理](/zh-TW/advanced/package-versioning.md)
- [回應（Response）](/zh-TW/responses.md)
