0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

Laravelで動的にサイトマップを生成する方法

Last updated at Posted at 2025-10-15

背景

「Laravel 動的サイトマップ」で検索すると、laravelium/sitemapパッケージを使ったやり方が出てきますが、現在はこの laravelium/sitemap がメンテナンスされておらず、今後のLaravelバージョンで動作保証されていません。
公式に推奨されている代替パッケージは:
rumenx/php-sitemap

です。調べてもあまり出てこなかった、かつ、AIが嘘をついてきたので、記事にしました。

導入方法

ステップ①:パッケージインストール

composer require rumenx/php-sitemap

ステップ②:ルート設定(routes/web.php)

use App\Http\Controllers\SitemapController;

Route::get('/sitemap.xml', [SitemapController::class, 'index']);

ステップ③:コントローラ作成

php artisan make:controller SitemapController

ステップ④:コントローラ編集

なぜかAIはAddUrl()という存在しないライブラリを使ってきますが、正確には以下のようにadd()です。

SitemapController.php
<?php

namespace App\Http\Controllers;

use Illuminate\Http\Response;
use Rumenx\Sitemap\Sitemap;
use App\Models\Post;

class SitemapController extends Controller
{
    public function index()
    {
        $sitemap = new Sitemap();

        // 固定ページ(以下は例です。他の固定ページをここに追記)
        $sitemap->add(url('/'), now()->toAtomString(), '1.0', 'daily');
        $sitemap->add(url('/about'), now()->toAtomString(), '0.8', 'monthly');
        

        // 動的ページ:post テーブルがあればこんな感じです
        $posts = Post::where('status', 'published')->get();

        foreach ($posts as $post) {
            $sitemap->add(
                url("/posts/{$post->slug}"),
                $post->updated_at->toAtomString(),
                '0.8',
                'weekly'
            );
        }

        $xml = $sitemap->renderXml();

        return response($xml, 200)
            ->header('Content-Type', 'application/xml');
    }
}

以上。

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?