Readouble

Laravel 13.x Laravel Head

イントロダクションIntroduction

Laravel Headは、タイトルやメタタグ、Open Graphメタデータ、正規URL、robots指示子、パフォーマンスヒント、構造化データなど、アプリケーションのドキュメントの<head>要素を管理するための流暢なAPIを提供します。Blade、Livewire、およびInertiaで動作します。Laravel Head[https://github.com/laravel/head] provides a fluent API for managing your application's document <head> element, including title and meta tags, Open Graph metadata, canonical URLs, robots directives, performance hints, and structured data. It works with Blade, Livewire, and Inertia.

インストールInstallation

Composerパッケージマネージャを使用してLaravel Headをインストールできます。You may install Laravel Head using the Composer package manager:

composer require laravel/head

クイックスタートQuickstart

サービスプロバイダでサイト全体に適用するデフォルト値を登録します。Register site-wide defaults in a service provider:

use Laravel\Head\Facades\Head;
use Laravel\Head\HeadBuilder;

Head::defaults(fn (HeadBuilder $head) => $head
    ->title('Laravel', suffix: ' - Laravel')
    ->description('Build something great.'));

実行時にページ固有のメタデータを設定します。Set page-specific metadata at runtime:

Head::title($post->title)
    ->description($post->description);

レイアウト内で解決したタグをレンダリングします。Render the resolved tags in your layout:

<head>
    @head
</head>

解決の優先順位Resolution Precedence

ページのメタデータは、優先度の低い順に以下の5つの層から解決します。Page metadata resolves from five layers, listed from lowest to highest priority:

  1. ページのデフォルトPage defaults
  2. ルートグループのメタデータRoute group metadata
  3. ルートメタデータRoute metadata
  4. 実行時メタデータRuntime metadata
  5. エラーメタデータError metadata

優先度の高い層は、低い層のフィールドをフィールド単位で置き換えます。例えば、実行時のタイトルはルートのタイトルを置き換えますが、ルートのドキュメント説明文(description)は置き換えません。以下のセクションでは、各層でメタデータを設定する方法を説明します。Blade、Livewire、Inertiaで解決されたメタデータをレンダリングする方法の詳細は、レンダリングを参照してください。Higher layers replace lower layers field by field. For example, a runtime title replaces the route title without replacing the route description. The sections that follow describe how to set metadata at each layer. For information about rendering the resolved metadata in Blade, Livewire, and Inertia, see Rendering[#rendering].

メタデータの定義Defining Metadata

Laravel Headを使用すると、サイト全体のデフォルト、ルートメタデータ、実行時呼び出し、エラーページ定義を使用してメタデータを定義できます。Laravel Head allows you to define metadata using site-wide defaults, route metadata, runtime calls, and error page definitions.

デフォルトDefaults

サービスプロバイダでページのデフォルト値を登録します。Register page defaults in a service provider:

use Laravel\Head\Enums\OgType;
use Laravel\Head\Facades\Head;
use Laravel\Head\HeadBuilder;

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

デフォルト値は、最も優先順位の低いページメタデータ層です。ルート、実行時、またはエラーメタデータがタイトルを設定しない場合、Laravelをそのままレンダリングします。より高い層がページタイトルを設定する場合、継承したサフィックスを適用するため、Head::title('About')About - Laravelとしてレンダリングします。継承したプレフィックスやサフィックスを無視するタイトルには、exact: trueを渡してください。Defaults are the lowest-priority page metadata layer. If no route, runtime, or error metadata sets a title, Laravel renders as-is. When a higher layer sets a page title, the inherited suffix is applied, so Head::title('About') renders About - Laravel. Pass exact: true for titles that should ignore an inherited prefix or suffix.

Head::canonical()を呼び出すと、現在のリクエストURLを使用して正規URLをレンダリングします。明示的にURLを設定するには、Head::canonical('/about')のように文字列を渡します。正規URLはデフォルトでhttpsに正規化します。リクエストスキームを保持するには、forceHttps: falseを渡してください。Calling Head::canonical() renders a canonical URL using the current request URL. To set an explicit URL, pass a string such as Head::canonical('/about'). Canonical URLs are normalized to https by default; pass forceHttps: false to preserve the request scheme.

robots指示子は、生文字列、RobotsRule Enumケース、あるいは両方の形式を混在させたリストとして渡せます。リストはカンマ区切りの指示子としてレンダリングするため、Head::robots([RobotsRule::NoIndex, RobotsRule::NoFollow])noindex, nofollowをレンダリングします。Robots directives may be passed as a raw string, as RobotsRule enum cases, or as a list mixing both forms. Lists are rendered as comma-separated directives, so Head::robots([RobotsRule::NoIndex, RobotsRule::NoFollow]) renders noindex, nofollow.

利便性のために、searchableByRobotsメソッドはallをレンダリングし、hiddenFromRobotsメソッドはnoneをレンダリングします。For convenience, the searchableByRobots method renders all, while the hiddenFromRobots method renders none.

ルートメタデータRoute Metadata

ルート上で直接メタデータを定義できます。これは、メタデータが事前に判明しているセミスタティックなページで特に役立ちます。You may define metadata directly on routes, which is especially useful for semi-static pages whose metadata is known ahead of time.

ルートとグループRoutes and Groups

Route::view('/contact', 'contact')
    ->name('contact')
    ->withHead(
        title: 'Contact Us',
        description: 'Get in touch.',
    );

共有ルートメタデータは、チェーン内の任意の場所でグループに適用できます。Shared route metadata may be applied to a group at any position in the chain:

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

リソースルートおよびシングルトンルートのメタデータも定義できます。You may also define metadata for resource and singleton routes:

Route::resource('posts', PostController::class)->withHead(
    robots: 'index, follow',
);

Route::singleton('profile', ProfileController::class)->withHead(
    title: 'Your Profile',
);

withHeadメソッドは、LaravelネイティブのルートメタデータAPIを介してプレーンな配列を保存します。これは、headキーの下にネストした属性を指定してmetadataメソッドを呼び出すのと同じであるため、メタデータはキャッシュ済みルートとの互換性を維持します。The withHead method stores plain arrays through Laravel's native route metadata API. It is equivalent to calling the metadata method with the attributes nested under a head key, so the metadata remains compatible with cached routes.

エディタや静的解析が誤字を検出できるように、名前付き引数はLaravel Headの組み込みルートプロパティに意図的に限定しています。カスタムタグビルダで登録したルート属性は、extensionsを介して渡せます。The named arguments are intentionally limited to Laravel Head's built-in route properties so editors and static analysis can catch misspelled names. Route attributes registered by custom tag builders may be passed through extensions:

Route::get('/article', ArticleController::class)->withHead(
    title: 'Article',
    extensions: ['readingTime' => 4],
);

サポートしているプロパティSupported Properties

サポートしているルートプロパティは、流暢なビルダメソッドと同じ名前に対応しています。The supported route properties map to the same names as the fluent builder methods:

カテゴリCategory プロパティProperties
ドキュメントDocument title, description, canonical, robotstitle, description, canonical, robots
アプリケーションメタデータApplication metadata themeColor, applicationName, colorScheme, referrer, viewport, appleWebAppTitle, webAppCapable, appleWebAppStatusBarStylethemeColor, applicationName, colorScheme, referrer, viewport, appleWebAppTitle, webAppCapable, appleWebAppStatusBarStyle
ソーシャルSocial og, ogImage, ogVideo, ogAudio, twitter, twitterImageog, ogImage, ogVideo, ogAudio, twitter, twitterImage
パフォーマンスPerformance preload, prefetch, preconnect, dnsPrefetchpreload, prefetch, preconnect, dnsPrefetch
検出Discovery alternates, feed, icon, favicon, appleTouchIcon, appleTouchStartupImage, maskIcon, manifestalternates, feed, icon, favicon, appleTouchIcon, appleTouchStartupImage, maskIcon, manifest
構造化データStructured data schemaschema
カスタムタグCustom tags meta, linkmeta, link

ネストしたオプション名は、流暢なAPIと同じcamelCase命名(forceHttpssiteNamesecureUrlなど)を使用します。Nested option names use the same camelCase naming as the fluent API, such as forceHttps, siteName, and secureUrl.

ogImagepreloadfeedschemaiconappleTouchStartupImageなどの繰り返し可能なプロパティは、単一の値またはリストのいずれかを受け入れます。Repeatable properties, such as ogImage, preload, feed, schema, icon, and appleTouchStartupImage, accept either a single value or a list.

実行時メタデータRuntime Metadata

表示中の投稿のタイトルなど、リクエストが到達するまで値が判明しない場合は、実行時に設定できます。When a value isn't known until a request arrives, such as the title of a post being viewed, you may set it at runtime:

use Laravel\Head\Facades\Head;

public function __invoke(Post $post): Response
{
    Head::title($post->title);

    // ...
}

Headファサードを介して行う実行時呼び出しは、リクエスト依存データのためにルートメタデータをオーバーライドします。コントローラやアクションは、こうした呼び出しを行う最も一般的な場所です。Runtime calls made via the Head facade override route metadata for request-dependent data. Controllers and actions are the most common places to make these calls:

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]);
}

複数の実行時呼び出しは、実行した順序でマージします。タイトル、ドキュメント説明文(description)、正規URL、robots指示子などの単一値フィールドの場合、後からの呼び出しを優先します。繰り返し可能なフィールドは複数のエントリを保持しますが、同じキーを再度追加すると前のエントリを更新します。ogImageメソッドの場合、URLがキーになります。Multiple runtime calls are merged in the order they run. For single-value fields such as title, description, canonical URL, and robots directives, the later call takes precedence. Repeatable fields retain multiple entries, but adding the same key again updates the earlier entry. For the ogImage method, the URL is the key:

Head::ogImage('/images/cover.jpg', alt: 'Draft cover')
    ->ogImage('/images/gallery.jpg', alt: 'Gallery image')
    ->ogImage('/images/cover.jpg', alt: 'Final cover', width: 1200, height: 630);
<meta property="og:image" content="/images/cover.jpg">
<meta property="og:image:width" content="1200">
<meta property="og:image:height" content="630">
<meta property="og:image:alt" content="Final cover">
<meta property="og:image" content="/images/gallery.jpg">
<meta property="og:image:alt" content="Gallery image">

デフォルト値から継承したOpen Graphメディアはフォールバックとして機能します。ルート、実行時、またはエラーメタデータが同じタイプの固有メディアを定義している場合、デフォルトメディアはマージせずに置換するため、ページのog:imageがサイト全体のデフォルト画像を優先します。Open Graph media inherited from your defaults acts as a fallback. When route, runtime, or error metadata defines its own media of the same type, the default media is replaced instead of merged, so a page's og:image takes precedence over a site-wide default image.

whenメソッドとunlessメソッドを使用して、条件付きメタデータを流暢に定義できます。You may fluently define conditional metadata using the when and unless methods:

Head::title($post->title)
    ->when($post->isDraft(), fn ($head) => $head->hiddenFromRobots());

エラーページError Pages

通常、アプリケーションのAppServiceProviderクラスのbootメソッド内でエラーメタデータを登録する必要があります。Typically, you should register error metadata within the boot method of your application's AppServiceProvider class:

use Laravel\Head\ErrorPages;
{use Laravel\Head\Facades\Head;

/**
 * アプリケーションの全サービスの起動処理
 */
public function boot(): void
{
    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.',
        );
    });
}

defaultsメソッドとstatusメソッドも、Head::defaults()が使用するのと同じ流暢なビルダコールバックを受け入れます。The defaults and status methods also accept the same fluent builder callback used by Head::defaults():

use Laravel\Head\ErrorPages;
use Laravel\Head\Facades\Head;
use Laravel\Head\HeadBuilder;

Head::errors(function (ErrorPages $errors) {
    $errors->status(404, fn (HeadBuilder $head) => $head
        ->title('Page Not Found')
        ->description('The page you are looking for could not be found.'));
});

登録したエラーステータスに対してレスポンスをレンダリングする場合、そのメタデータが他のすべての層よりも優先します。When a response is rendered for a registered error status, that metadata takes precedence over every other layer.

Laravelは、エラービューをレンダリングするとき、またはInertiaのhandleExceptionsUsing()メソッドなどのレスポンスフェーズフックを実行するときに、レスポンスステータスを自動的に検出します。$exceptions->render()コールバック内でエラーレスポンスをレンダリングする場合は、エラーメタデータを適用するように、レンダリングする前にHead::status(404)を呼び出してください。Laravel automatically detects the response status when rendering an error view or executing a respond-phase hook such as Inertia's handleExceptionsUsing() method. If you render an error response inside an $exceptions->render() callback, call Head::status(404) before rendering so the error metadata is applied.

Open GraphOpen Graph

ogメソッドを使用してOpen Graphプロパティを設定できます。繰り返し可能なメディアは、名前付き引数を直接受け入れるトップレベルのメソッドを使用して追加できます。You may set Open Graph properties using the og method. Repeatable media may be added using the top-level methods, which accept named arguments directly:

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,
    );

ogImageogVideoogAudioの各メソッドは、第1引数としてURLを受け入れ、Open Graph仕様でサポートしているaltwidthheighttypesecureUrlなどのオプションの名前付き引数も受け入れます。The ogImage, ogVideo, and ogAudio methods accept a URL as their first argument, along with optional named arguments such as alt, width, height, type, and secureUrl where supported by the Open Graph specification.

ImageType::SvgImageType::PngImageType::JpegImageType::Webpなど、APIが画像のtypeを受け入れる場所であればどこでも、画像MIMEタイプをImageType Enumケースとして渡せます。You may pass image MIME types as ImageType enum cases anywhere the API accepts an image type, such as ImageType::Svg, ImageType::Png, ImageType::Jpeg, and ImageType::Webp.

note Note: ドキュメントのtitledescriptionは、欠落しているog:titleog:descriptionの値を自動的に補完します。[!NOTE] Document title and description automatically fill missing og:title and og:description values.

他の属性がない単一のOpen Graph画像の場合は、ogメソッドにimage名前付き引数を渡せます。For a single Open Graph image with no other attributes, you may pass the image named argument to the og method:

Head::og(
    type: OgType::Website,
    title: $page->title,
    description: $page->description,
    image: $page->og_image_url,
);

og(image: ...)呼び出しとogImage(...)呼び出しは、同じ内部画像リストに書き込むため、呼び出し場所でより表現力豊かな方を使用できます。プロダクトや記事のプロパティなどのカスタムOpen Graph拡張機能には、metaメソッドを使用できます。The og(image: ...) and ogImage(...) calls write to the same underlying image list, so you may use whichever is more expressive at the call site. You may use the meta[#custom-tags] method for custom Open Graph extensions such as product or article properties.

X/TwitterカードX / Twitter Cards

Open Graphが使用するのと同じタイトル、説明文、画像からX/Twitterカードをレンダリングするには、デフォルト値にtwitter()を登録します。To render X / Twitter cards from the same title, description, and image used by Open Graph, register twitter() in your defaults:

use Laravel\Head\Enums\TwitterCard;
use Laravel\Head\Facades\Head;
use Laravel\Head\HeadBuilder;

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

次に、ページレベルのメタデータを設定します。Then set page-level metadata:

Head::title('Introducing Laravel Head')
    ->description('A fluent API for Laravel document head metadata.')
    ->ogImage('[https://example.com/social.jpg](https://example.com/social.jpg)', alt: 'Introducing Laravel Head');

これにより、一致するTwitterタグをレンダリングします。This renders matching Twitter tags:

<meta name="twitter:card" content="summary_large_image">
<meta name="twitter:title" content="Introducing Laravel Head">
<meta name="twitter:description" content="A fluent API for Laravel document head metadata.">
<meta name="twitter:image" content="[https://example.com/social.jpg](https://example.com/social.jpg)">
<meta name="twitter:image:alt" content="Introducing Laravel Head">

明示的なTwitterの値を指定して、個別ページをカスタマイズできます。You may customize individual pages with explicit Twitter values:

Head::twitter(title: $post->social_title)
    ->twitterImage($post->social_image_url, alt: $post->title);

ルートメタデータはtwittertwitterImageを受け入れます。Route metadata accepts twitter and twitterImage.

テーマカラーTheme Colors

テーマカラーは、グローバル、ルート単位、または実行時に設定できます。You may set theme colors globally, per route, or at runtime:

Head::themeColor('#0f172a');

これは<meta name="theme-color">タグをレンダリングします。メディア固有のテーマカラーには、Media Enumを使用できます。This renders a <meta name="theme-color"> tag. For media-specific theme colors, you may use the Media enum:

use Laravel\Head\Enums\Media;

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

Media EnumにはPortraitLandscapeも含まれています。media引数は、カスタムメディアクエリ文字列も受け入れます。The Media enum also includes Portrait and Landscape. The media argument also accepts a custom media query string.

ルートメタデータは、同じcamelCaseキーによる単一のテーマカラーをサポートしています。Route metadata supports a single theme color through the same camelCase key:

Route::view('/dashboard', 'dashboard')->withHead(
    themeColor: '#0f172a',
);

アプリケーションメタデータとアイコンApplication Metadata and Icons

Laravel Headには、一般的なブラウザおよびアプリケーションメタデータ用のメソッドが含まれています。Laravel Head includes methods for common browser and application metadata:

use Laravel\Head\Enums\ImageType;
use Laravel\Head\Enums\Media;

Head::applicationName('Laravel')
    ->colorScheme('light dark')
    ->referrer('strict-origin-when-cross-origin')
    ->viewport('width=device-width, initial-scale=1')
    ->appleWebAppTitle('Laravel')
    ->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メソッドのエイリアスであり、同じtypesizesmedia引数を受け入れます。The favicon method is an alias for the icon method and accepts the same type, sizes, and media arguments.

ルートメタデータも同じ名前を使用します。Route metadata uses the same names:

use Laravel\Head\Enums\ImageType;
use Laravel\Head\Enums\Media;

Route::view('/dashboard', 'dashboard')->withHead(
    applicationName: 'Laravel',
    colorScheme: 'light dark',
    appleWebAppTitle: 'Laravel',
    webAppCapable: true,
    appleWebAppStatusBarStyle: 'black',
    favicon: [
        ['href' => '/favicon.svg', 'type' => ImageType::Svg],
        ['href' => '/favicon-32x32.png', 'type' => ImageType::Png, 'sizes' => '32x32'],
    ],
    appleTouchIcon: ['href' => '/apple-touch-icon.png', 'sizes' => '180x180'],
    appleTouchStartupImage: ['href' => '/launch.png', 'media' => Media::Portrait],
    manifest: '/site.webmanifest',
);

プログレッシブウェブアプリ(PWA)Progressive Web Apps

pwaメソッドは、インストール可能なウェブアプリに必要な一般的なドキュメント<head>タグを設定します。The pwa method configures the common document <head> tags needed for an installable web app:

Head::pwa(
    name: 'Laravel',
    manifest: '/site.webmanifest',
    themeColor: '#0f172a',
    appleTouchIcon: '/apple-touch-icon.png',
    appleWebAppStatusBarStyle: 'black',
);

これはアプリケーション名、ウェブアプリケーションマニフェストリンク、およびiOSスタンドアロンメタデータをレンダリングします。指定した場合、テーマカラー、Appleステータスバーのスタイル、Appleタッチアイコンもレンダリングします。ウェブアプリケーションマニフェストの作成とサービスワーカの登録は、引き続きアプリケーション側の責任です。This renders the application name, web application manifest link, and iOS standalone metadata. If provided, the theme color, Apple status bar style, and Apple touch icon are also rendered. Creating the web application manifest and registering a service worker remain your application's responsibility.

pwaメソッドはデフォルト値または実行時メタデータで使用できます。ルートメタデータは、上記に示す個別のプロパティをサポートしています。You may use the pwa method in defaults or runtime metadata. Route metadata supports the individual properties shown above.

パフォーマンスと検出Performance and Discovery

Laravel Headは、パフォーマンスヒント、ペジネーションリンク、ロケール代替、フィード検出をレンダリングします。Laravel Head renders performance hints, pagination links, locale alternates, and feed discovery:

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

ローカルアセットの場合、preloadAsset()およびprefetchAsset()asset()ヘルパを介してURLを解決し、ファイル拡張子からas属性を検出します。フォントのプリロードにはcrossoriginが自動的に含まれます。これは、プリロードの仕様により同一オリジンのフォントであっても必要とされるためです。For local assets, preloadAsset() and prefetchAsset() resolve the URL through the asset() helper and detect the as attribute from the file extension. Font preloads automatically include crossorigin, which the preload specification requires even for same-origin fonts:

Head::preloadAsset('fonts/inter.woff2')
    ->prefetchAsset('images/next.webp');
<link rel="preload" href="[https://example.com/fonts/inter.woff2](https://example.com/fonts/inter.woff2)" as="font" crossorigin>
<link rel="prefetch" href="[https://example.com/images/next.webp](https://example.com/images/next.webp)" as="image">

明示的にasを渡して検出をオーバーライドできます。ブラウザはこの属性がないプリロードを無視するため、拡張子からas属性を検出できない場合、preloadAssetメソッドは例外を投げます。prefetchAssetメソッドは単にそれを省略します。You may pass as explicitly to override detection. The preloadAsset method will throw an exception when the as attribute cannot be detected from the extension because browsers ignore preloads without this attribute; the prefetchAsset method will simply omit it.

カスタムタグCustom Tags

専用メソッドのないタグには、meta()link()を使用します。For tags without a dedicated method, use meta() and link():

Head::meta('format-detection', 'telephone=no')
    ->meta('article:author', $post->author->name)
    ->link('search', '/opensearch.xml', [
        'type' => 'application/opensearchdescription+xml',
        'title' => 'Laravel Search',
    ])
    ->link('me', '[https://social.example.com/@laravel](https://social.example.com/@laravel)');

一致する条件の下でのみブラウザがタグを適用すべき場合は、metaタグにメディアクエリを含められます。You may include a media query on a meta tag when the browser should only apply the tag under matching conditions:

use Laravel\Head\Enums\Media;

Head::meta('theme-color', '#ffffff', media: Media::Light)
    ->meta('theme-color', '#111827', media: Media::Dark);

metaメソッドは、通常のmetaタグにはname属性を使用します。Open Graph(og:)や記事メタデータ(article:)など、通常property属性を使用するキーの場合、メソッドは自動的に切り替えます。The meta method uses the name attribute for regular meta tags. For keys that typically use the property attribute, such as Open Graph (og:) or article metadata (article:), the method switches automatically:

Head::meta('description', 'About Laravel')
    ->meta('og:title', 'About Laravel');
<meta name="description" content="About Laravel">
<meta property="og:title" content="About Laravel">

property: trueまたはproperty: falseを渡して、どちらの属性かを明示的に選択できます。You may pass property: true or property: false to explicitly select either attribute.

スキーマSchemas

組み込みのスキーマビルダは、一般的なJSON-LDタイプをカバーしています。Built-in schema builders cover the common JSON-LD types:

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)
        )
);

組み込みのファクトリメソッドは、articleblogPostingproductofferbrandbreadcrumbsfaqorganizationpersonwebPage、およびwebSiteです。未知のファクトリメソッドは汎用スキーマオブジェクトを作成するため、カスタムのschema.orgタイプを表現することも可能です。The built-in factory methods are article, blogPosting, product, offer, brand, breadcrumbs, faq, organization, person, webPage, and webSite. Unknown factory methods create a generic schema object, so you can still express custom schema.org types.

JSON-LDスキーマデータが無効な場合、Laravel Headは本番以外の環境で例外を投げ、本番環境で警告をログに記録します。When JSON-LD schema data is invalid, Laravel Head throws an exception in non-production environments and logs a warning in production.

パンくずリストBreadcrumbs

ブレッドクラム項目は、一度に1つずつ、またはまとめて追加できます。位置は項目を追加した順序で自動的に割り当てます。Breadcrumb items may be added one at a time or in bulk. Positions are assigned automatically in the order the items are added:

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

単一のブレッドクラム項目を追加するには、itemメソッドを使用できます。You may use the item method to append a single breadcrumb item:

Schema::breadcrumbs()
    ->item('Home', route('home'))
    ->item('Shop', route('shop.index'));

FAQFAQs

FAQエントリも同じパターンに従います。questionメソッドを使用して一度に1つずつ追加するか、questionsメソッドを使用してまとめて追加できます。FAQ entries follow the same pattern. You may add them one at a time using the question method or in bulk using the questions method:

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.',
    ])
);

カスタムスキーマCustom Schemas

カスタムスキーマタイプを明示的に登録できます。You may explicitly register custom schema types:

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);

Head::schema(
    Schema::jobPosting()
        ->title('Senior Laravel Developer')
        ->datePosted(now())
);

レンダリングRendering

Laravel Headは、現在のレスポンス向けにページのメタデータをタグに解決します。これらのタグをレンダリングする方法は、アプリケーションスタックによって異なります。Laravel Head resolves page metadata into tags for the current response. How these tags are rendered depends on your application stack.

HTMLレンダラは、@headディレクティブと、Laravel Headがhead Propを介してInertiaと共有するレンダリング済み要素を駆動します。配列レンダラは、解決されたメタデータを構造化データとして必要とするアプリケーション向けにHead::toArray()を駆動します。The HTML renderer powers the @head directive and the rendered elements that Laravel Head shares with Inertia via the head prop. The array renderer powers Head::toArray() for applications that need the resolved metadata as structured data.

BladeBlade

レイアウトの<head>内で、蓄積されたタグを@headディレクティブでレンダリングします。Render the accumulated tags in your layout's <head> with the @head directive:

<head>
    <meta charset="utf-8">
    @head
</head>

@headディレクティブは同期的にレンダリングするため、レイアウトをレンダリングする前にページのメタデータを定義する必要があります。The @head directive renders synchronously, so you should define page metadata before the layout is rendered.

LivewireLivewire

Livewireアプリケーションは、ドキュメントレイアウト内で同じ@headディレクティブを使用します。Livewire applications use the same @head directive in their document layout:

<head>
    @head
</head>

<body>
    {{ $slot }}

    @livewireScripts
</body>

Livewire固有の設定は不要です。Laravel Headのメタデータはリクエスト単位で解決し、リゾルバはリクエストにスコープされます。したがって、wire:navigateによる遷移のたびに新しいドキュメントを取得し、その@head出力には移動先ルートのメタデータを反映します。wire:navigateを使用して表示したページは、コンポーネントレベルのheadコードを必要とすることなく、適切なルート、実行時、およびエラーのメタデータを受け取ります。No Livewire-specific configuration is required. Laravel Head metadata is resolved per request, and the resolver is request-scoped. Therefore, each wire:navigate visit fetches a fresh document whose @head output reflects the destination route's metadata. Pages visited using wire:navigate receive the appropriate route, runtime, and error metadata without requiring component-level head code.

InertiaInertia

Inertiaのルートテンプレート内で、Inertia自身のコンポーネントと並べて同じ@headディレクティブを使用します。Use the same @head directive in your Inertia root template, alongside Inertia's own components:

<html>
<head>
    <meta charset="utf-8">
    @head

    @viteReactRefresh
    @vite(['resources/css/app.css', 'resources/js/app.tsx'])
    <x-inertia::head />
</head>
<body>
    <x-inertia::app />
</body>
</html>

Inertiaをインストールすると、Laravel Headはすべてのページオブジェクト上のhead Propの下に、レンダリングされた要素文字列の配列として、ページ管理下のheadを自動的に共有します。When Inertia is installed, Laravel Head automatically shares the page-managed head as an array of rendered element strings under a head prop on every page object:

{
    "props": {
        "head": [
            "<title data-inertia=\"title\">Dashboard - Laravel</title>",
            "<meta data-inertia=\"description\" name=\"description\" content=\"Your application overview.\">"
        ]
    }
}

アプリケーションがcreateInertiaApp()を呼び出す場所で、InertiaのserverHeadオプションを有効にしてください。このオプションはInertia 3.5以降で利用できます。Enable Inertia's serverHead option wherever your application calls createInertiaApp(). The option is available in Inertia 3.5 and later:

createInertiaApp({
    // ...
    serverHead: true,
});

ページ管理下の各要素には安定したdata-inertiaキーが存在します。@headディレクティブが最初のドキュメントをレンダリングした後、Inertiaがそれらの要素を引き継ぎ、通常の訪問、インスタント訪問、および「戻る・進む」のナビゲーション中に同期を保ちます。要素は最初のHTMLレスポンス内に存在するため、クローラやリンクプレビューのボットはJavaScriptを実行することなくそれらを読み込めます。クライアント側の<Head>コンポーネントは不要です。Each page-managed element has a stable data-inertia key. The @head directive renders the initial document, after which Inertia adopts those elements and keeps them synchronized during standard visits, instant visits[https://inertiajs.com/docs/v3/the-basics/instant-visits], and back and forward navigation. The elements are present in the initial HTML response, so crawlers and link-preview bots can read them without executing JavaScript. No client-side <Head> component is required.

これはサーバサイドレンダリング(SSR)の有無にかかわらず動作します。アプリケーションに個別のSSRエントリポイントがある場合は、そこでもserverHeadを有効にしてください。Laravel Headは、JavaScript SSRが生成した他のhead要素を保持しつつ、順序に関係なく@head<x-inertia::head />の間でページ管理下の要素を自動的に重複除外します。This works with or without server-side rendering (SSR)[https://inertiajs.com/docs/v3/advanced/server-side-rendering]. If your application has a separate SSR entry point, enable serverHead there too. Laravel Head automatically deduplicates page-managed elements between @head and <x-inertia::head />, regardless of their order, while preserving other head elements produced by JavaScript SSR.

note Note: 既存のInertiaアプリケーションにLaravel Headを追加する場合は、Laravel Headが最終的なドキュメントタイトルを管理できるように、resources/js/app.tsxおよびresources/js/ssr.tsxからタイトルのコールバックを削除し、両者が同じ要素を定義しないようにInertiaの<Head>コンポーネントが管理するタグをLaravel Headへ移動してください。[!NOTE] When adding Laravel Head to an existing Inertia application, remove any title callbacks from resources/js/app.tsx and resources/js/ssr.tsx so Laravel Head can manage the final document title, and move tags managed by Inertia's <Head> component[https://inertiajs.com/docs/v3/the-basics/title-and-meta] into Laravel Head so the two never define the same element.

head Propは部分リロードのレスポンスからは省略するため、Inertiaは最後のフルページのheadを保持します。同様に、インスタント訪問でもバックグラウンドレスポンスが到着するまで現在のheadを保持します。アプリケーションがすでにhead Propを使用している場合は、サービスプロバイダでその名前を変更してください。The head prop is omitted from partial reload responses, so Inertia retains the last full page's head. Instant visits likewise retain the current head until the background response arrives. If your application already uses the head prop, change its name in a service provider:

use Laravel\Head\Facades\Head;

public function boot(): void
{
    Head::inertia(prop: '_head');
}

次に、serverHead: '_head'でInertiaが同じPropを指すように指定します。Then point Inertia at the same prop with serverHead: '_head'.

スタティックInertiaタグStatic Inertia Tags

Laravel Headが各ページに適切な値を解決できるように、ほとんどのタグはデフォルト値、ルートメタデータ、または実行時メタデータに含める必要があります。Inertiaグローバルは、最初のHTMLレスポンスでレンダリングされ、セッションの残りの部分でInertiaによって変更されないドキュメントタグにのみ使用してください。Most tags should live in defaults, route metadata, or runtime metadata so Laravel Head can resolve the right value for each page. Use Inertia globals only for document tags rendered in the first HTML response and left unchanged by Inertia for the rest of the session.

サービスプロバイダでHead::inertiaGlobals()を使用して登録します。Register them in a service provider with Head::inertiaGlobals():

use Laravel\Head\Facades\Head;
use Laravel\Head\HeadBuilder;

Head::inertiaGlobals(function (HeadBuilder $head) {
    $head
        ->viewport('width=device-width, initial-scale=1')
        ->colorScheme('light dark')
        ->icon('/favicon.svg', type: 'image/svg+xml')
        ->appleTouchIcon('/apple-touch-icon.png', sizes: '180x180')
        ->manifest('/site.webmanifest');
});

Inertiaグローバルはhead Propから除外され、data-inertia所有権属性なしでレンダリングされ、最初のレスポンス以降に更新することは一切ありません。これらのグローバルは、ビューポート、カラー構成、ファビコン、タッチアイコン、マニフェストなど、安定したブラウザヒントに適しています。タグがページ固有である場合、SEOに関連する場合、または後でオーバーライドする可能性がある場合は、代わりにdefaults、ルートメタデータ、または実行時メタデータに配置してください。Inertia globals are excluded from the head prop, rendered without data-inertia ownership attributes, and never updated after the first response. These globals are suitable for stable browser hints such as viewport, color scheme, favicons, touch icons, and manifests. If a tag is page-specific, SEO-relevant, or may be overridden later, put it in defaults, route metadata, or runtime metadata instead.

レンダリングされたタグの代わりに構造化データとして解決されたメタデータを必要とするアプリケーションは、Head::toArray()を呼び出すことができます。返されるデータには、タイトル、Open Graphの値、JSON-LDスキーマ、およびその他の解決されたメタデータを含みます。Applications that need the resolved metadata as structured data instead of rendered tags may call Head::toArray(). The returned data includes titles, Open Graph values, JSON-LD schemas, and other resolved metadata.

章選択

設定

明暗テーマ
light_mode
dark_mode
brightness_auto システム設定に合わせる
テーマ選択
photo_size_select_actual デフォルト
photo_size_select_actual モノクローム(白黒)
photo_size_select_actual Solarized風
photo_size_select_actual GitHub風(青ベース)
photo_size_select_actual Viva(黄緑ベース)
photo_size_select_actual Happy(紫ベース)
photo_size_select_actual Mint(緑ベース)
コードハイライトテーマ選択

明暗テーマごとに、コードハイライトのテーマを指定できます。

テーマ配色確認
スクリーン表示幅
640px
80%
90%
100%

768px以上の幅があるときのドキュメント部分表示幅です。

インデント
無し
1rem
2rem
3rem
原文確認
原文を全行表示
原文を一行ずつ表示
使用しない

※ 段落末のEボタンへカーソルオンで原文をPopupします。

Diff表示形式
色分けのみで区別
行頭の±で区別
削除線と追記で区別

※ [tl!…]形式の挿入削除行の表示形式です。

テストコード表示
両コード表示
Pestのみ表示
PHPUnitのみ表示
OS表示
全OS表示
macOSのみ表示
windowsのみ表示
linuxのみ表示
JSフレームワーク
両フレームワーク
Reactのみ表示
Vueのみ表示
Svelteのみ表示
JSのみ表示

(JSが存在しない場合は、他を全表示)

和文変換

対象文字列と置換文字列を半角スペースで区切ってください。(最大5組各10文字まで)

本文フォント

総称名以外はCSSと同様に、"〜"でエスケープしてください。

コードフォント

総称名以外はCSSと同様に、"〜"でエスケープしてください。

保存内容リセット

localStrageに保存してある設定項目をすべて削除し、デフォルト状態へ戻します。

ヘッダー項目移動

キーボード操作